[英]Laravel 6 Eloquent - Relationship between three tables and pivots
[英]Laravel - Eloquent way to connect three tables using two pivots
Laravel 新手,
我有三个表users
、 roles
和permissions
。 这些与以下两个数据透视表role_user
和permission_role
在这里我想连接三个表,这样我就可以得到像多对多和一对多关系这样的结果。 例如,我可以获得给定用户的所有权限和角色(一对多),反之亦然,以获得彼此的角色和权限。 另外,我想获取所有用户以及各自的角色和权限,反之亦然。
我刚刚在社区的帮助下解决了为给定用户获取角色的问题,但现在我坚持获得上述结果。 谁能帮我实现它?
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function roles() {
return $this->belongsToMany('App\Admin\Role');
}
}
<?php
namespace App\Admin;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
protected $fillable = ['name', 'display'];
public function permissions()
{
return $this->belongsToMany('App\Admin\Permission');
}
public function admin_users()
{
return $this->belongsToMany('App\Admin\Admin');
}
public function users()
{
return $this->belongsToMany('App\User');
}
}
<?php
namespace App\Admin;
use Illuminate\Database\Eloquent\Model;
class Permission extends Model
{
protected $fillable = ['model', 'can'];
public function roles()
{
return $this->belongsToMany('App\Admin\Role');
}
}
首先感谢@He提供了一个方向。
所以在这里with()
我不得不添加roles
模型来调用它的permissions
方法。 所以代码将如下所示。
User::with('roles', 'roles.permissions')->find($id);
所以这里的roles.permissions
是Role
模型中的permissions()
方法
class Role extends Model
{
protected $fillable = ['name', 'display'];
public function permissions()
{
return $this->belongsToMany('App\Admin\Permission');
}
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.