laravel 5.4多对多关系 [英] laravel 5.4 many to many relationship
问题描述
我与pjt_role_admin有许多表'admins'和'pjt_roles'的关系. 但是,不起作用
我有2个模型
班级角色
protected $table = 'pjt_roles';
public function Admin(){
return $this->belongsToMany(Admin::class',pjt_role_admin');
}
班级管理员
public function Role(){
return $this->belongsToMany(Role::class,'pjt_role_admin');
}
和表pjt_role_admin
具有属性
-
表
-
admin_id 表
pjt_roles
中的 -
role_id
admins
中的
指定关系中的数据透视表.默认的laravel假定admin_role
作为数据透视表,因为您有Admin
和Role
模型
班级角色
protected $table = 'pjt_roles';
public function Admin(){ // should be admins() for better readability
return $this->belongsToMany(Admin::class, 'pjt_role_admin');
}
班级管理员
public function Role(){ // should be roles() for better readability
return $this->belongsToMany(Role::class, 'pjt_role_admin');
}
确定表的名称 关系的联接表,Eloquent将联接两个相关模型 名称按字母顺序排列.但是,您可以随意覆盖它 习俗.您可以通过将第二个参数传递给 includesToMany方法.
获取数据
$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/雄辩的关系#many-to-many
i have relationship many to many table 'admins' , 'pjt_roles' with pjt_role_admin. but,not working
i have 2 model
class Role
protected $table = 'pjt_roles';
public function Admin(){
return $this->belongsToMany(Admin::class',pjt_role_admin');
}
class Admin
public function Role(){
return $this->belongsToMany(Role::class,'pjt_role_admin');
}
and table pjt_role_admin
have attribute
admin_id from table
admins
role_id from table
pjt_roles
Specify your pivot table in relationship. Default laravel assume admin_role
as your pivot table because you have Admin
and Role
models
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.
Fetch Data
$admin = Admin::find(1);
$roles = $admin->Role; // should change to roles() in relationship for better readability
Save
$admin->Role()->attach($roleId);
details https://laravel.com/docs/5.4/eloquent-relationships#many-to-many
这篇关于laravel 5.4多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!