Laravel 5.5中的种子错误

时间:2017-12-04 09:53:27

标签: laravel-5.5 laravel-seeding

我正面临播种问题。我的AddressessTableSeeder.php文件如下所示

use Illuminate\Database\Seeder;

class AddressessTableSeeder extends Seeder
{
    public function run()
    {
        factory(App\Address::class, 50)->create()->each(function ($u) 
        {
            $u->users()->save(factory(App\User::class)->make());
        });
    }
}

我的Address.php文件如下所示

class Address extends Model
{
    protected $fillable = ['user_id', 'name', 'address','mobile_no','image','email'];

    public function users() {
        return $this->belongsTo(User::class);
    }
}

我收到如下错误

enter image description here

1 个答案:

答案 0 :(得分:1)

使用associate并在关联之前创建用户,这样您就可以在保存之前获取ID

factory(App\Address::class, 50)->create()->each(function ($u) 
{
    $u->users()->associate(factory(App\User::class)->create())->save();
});