laravel 5.4多对多关系 [英] laravel 5.4 many to many relationship

查看:111
本文介绍了laravel 5.4多对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我与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具有属性

    admins

    中的
  1. admin_id 表pjt_roles

  2. 中的
  3. role_id

解决方案

指定关系中的数据透视表.默认的laravel假定admin_role作为数据透视表,因为您有AdminRole模型

班级角色

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

  1. admin_id from table admins

  2. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆