database - laravel 5.4 多对多关系

标签 database laravel relationship

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

  1. admin_id 来自表 admins

  2. 来自表pjt_roles的role_id

enter image description here

最佳答案

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

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/

相关文章:

php - Wamp 服务器无法正确处理数据库的 PHP

php - 批量替换 phpMyadmin 中表字段中的所有值

自动索引的 SQL Server 2008 外键

symfony - Doctrine2一对多,自引用关系

c++ - 如何在 Windows 平台上从原生 C++ 处理 SQL Server?

Laravel:命令未找到

laravel - 在路由回调函数中使用 Eloquent 模型会出错

php - 获取特定值 Laravel

php - 连接表上的 Laravel 一元关系

sql-server - Windows 应用程序 (WPF) 的独立数据库