【发布时间】:2019-01-05 16:25:37
【问题描述】:
我需要在 Laravel 中建立关系,每个用户都有很多设备
用户模型
public function devices()
{
return $this->hasMany(Device::class);
}
设备模型
public function users()
{
return $this->belongsTo(User::class);
}
}
device_user 表
Schema::create('device_user', function (Blueprint $table) {
$table->increments('id');
$table->integer('device_id')->unsigned()->index();
$table->foreign('device_id')->references('id')->on('devices')->onDelete('cascade');
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->timestamps();
});
播种机
factory(App\Device::class, 20)->create()->each(function(App\Device $device) {
$device->users()->attach([
rand(1,5),
rand(6,15),
rand(16,20),
]);
});
但是,当我使用播种机运行迁移时,我收到了这条消息
Call to undefined method Illuminate\Database\Query\Builder::attach()
请帮忙
【问题讨论】:
标签: php laravel relationship seed