在拉拉威尔建立一对多的关系



我需要在Laravel中建立关系,其中每个用户都有许多设备

用户模型

public function devices()
{
return $this->hasMany(Device::class);
}

设备型号

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

}

设备用户表

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(AppDevice::class, 20)->create()->each(function(AppDevice $device) {
$device->users()->attach([
rand(1,5), 
rand(6,15), 
rand(16,20), 
]);
});

但是,当我使用seeder运行迁移时,我会收到以下消息

Call to undefined method IlluminateDatabaseQueryBuilder::attach()

请帮助

attach对于多对多关系,一对多关系不需要device_user表,在一对多中,您应该在device表中创建一个名称为user_id的列,然后就可以在设备表中插入user_id数据。并获取与的用户关系

Device::user()->get();

最新更新