【发布时间】:2020-05-13 12:55:14
【问题描述】:
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');
}
}
【问题讨论】:
-
您要获取的数据样本
-
我想获取用户字段以及角色和权限字段。
-
你不能通过 User::with('roles', 'permission')->find(id); ?
-
@Qonvex620 出现错误
Call to undefined relationship [permissions] on model [App\Admin\Admin]. -
如果你想访问用户的权限,你可以使用 hasManyThrough 在你的用户模型中创建一个有权限的关系