Laravel 8 - 使用已知值数组为数据库播种

Laravel 8 - Using an array of known values to seed the database

我有一个场景,我需要用一组将被引用的颜色填充 table。我在 Laravel 8 中找到了以下适合我的作品。我找不到关于这个主题的任何东西,所以我想我会分享。请对改进发表评论,或者如果有什么我本可以做的非常明显的事情,请告诉我。

播种者:

    public function run()
{

    $colours = [
        "Red" => "#ff4444",
        "Yellow" => "#ffbb33",
        "Green" => "#00C851",
        "Blue" => "#33b5e5",
        "Teal" => "#2BBBAD",
        "Purple" => "#aa66cc",
    ];
    
    foreach ($colours as $key => $value){
        $entity = colours::factory()->make();
        $entity->name = $key;
        $entity->hex = $value;
        $entity->save();
    }


}

工厂

    public function definition()
{
    return [
        'hex' => '#000000',
        'name' => 'example'
    ];
}

更新,Seeder可以更简单的写成

    $entity = colours::factory()->create(['name' => $key, 'hex' => $value]);