laravel 5.4 many to many relationship

时间秒杀一切 提交于 2019-12-10 10:45:41

问题


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

  1. admin_id from table admins

  2. role_id from table pjt_roles


回答1:


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



来源:https://stackoverflow.com/questions/51094443/laravel-5-4-many-to-many-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!