工厂播种时,字段对一对多关系

时间:2018-04-17 19:24:26

标签: laravel laravel-5 laravel-seeding

我有一个speciality可以有很多procedures

我想通过许多程序来培养专业。

型号:

特种

class Speciality extends Model
{

    protected $fillable = ['name'];

    public function procedures() {
        return $this->hasMany('App\Procedure');
    }
}

程序

class Procedure extends Model
{
    protected $fillable = ['speciality_id', 'name'];

    public function speciality() {
        return $this->belongsTo('App\Speciality');
    }
}

工厂:

特种

$factory->define(App\Speciality::class, function (Faker $faker) {
    return [
        'name' => 'Example'
    ];
});

程序

$factory->define(App\Procedure::class, function (Faker $faker) {
    return [
        'name' => $faker->realText(20)
    ];
});

接种:

public function run()
    {
        factory(App\Speciality::class)->create()
            ->each(function($speciality) {
                $speciality->procedures()
                    ->saveMany(factory(App\Procedure::class, rand(5,20))
                    ->make()
                );
        });
    }

显示的错误是:

  

SQLSTATE [HY000]:常规错误:1364字段' speciality_id'没有按'吨   有一个默认值(SQL:插入proceduresname,   updated_atcreated_at)值(这意味着很多。,2018-04-17   19:09:31,2018-04-17 19:09:31))

speciality_id未设置为procedure工厂内的值,因为它是专业的外键。但是我对使用$speciality->procedures()的理解是它会在播种时自动分配speciality_id。

为什么会发生此错误。非常感谢。

1 个答案:

答案 0 :(得分:0)

我可能在这里错了,但我认为只有一个小问题,当你致电make时:

public function run()
    {
        factory(App\Speciality::class)->create()
            ->each(function($speciality) {
                $speciality->procedures()
                    ->saveMany(factory(App\Procedure::class, rand(5,20))->make());     

        });
    }

之前从未将此与saveMany()一起使用,只有save(),但是尝试一下?