我与 pjt_role_admin 具有多对多表“admins”、“pjt_roles”的关系。 但是,不工作
我有 2 个模型
类角色
protected $table = 'pjt_roles';
public function Admin(){
return $this->belongsToMany(Admin::class',pjt_role_admin');
}
类(class)管理员
public function Role(){
return $this->belongsToMany(Role::class,'pjt_role_admin');
}
和表pjt_role_admin
有属性
admin_id 来自表
admins
来自表
pjt_roles
的role_id
最佳答案
指定关系中的数据透视表。默认 laravel 假设 admin_role
作为您的数据透视表,因为您有 Admin
和 Role
模型
class Role
protected $table = 'pjt_roles';
public function Admin(){ // should be admins() for better readability
return $this->belongsToMany(Admin::class, 'pjt_role_admin');
}
class Admin
public function Role(){ // should be roles() for better readability
return $this->belongsToMany(Role::class, 'pjt_role_admin');
}
To determine the table name of the relationship's joining table, Eloquent will join the two related model names in alphabetical order. However, you are free to override this convention. You may do so by passing a second argument to the belongsToMany method.
获取数据
$admin = Admin::find(1);
$roles = $admin->Role; // should change to roles() in relationship for better readability
保存
$admin->Role()->attach($roleId);
详情https://laravel.com/docs/5.4/eloquent-relationships#many-to-many
关于database - laravel 5.4 多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51094443/