[英]Laravel hasMany not returning collection
I am building the middleware for permissions. 我正在构建许可中间件。 Permissions are based on either user action types and/or module/element type (ie delete button). 权限基于用户操作类型和/或模块/元素类型(即删除按钮)。
The model ActionPermission
(table action_permission
) has all the permission types while table users__action_permission
is the pivot for User
& ActionPermission
with all users and their permission IDs. 模型ActionPermission
(表action_permission
)具有所有权限类型,而表users__action_permission
是User
& ActionPermission
其中包含所有用户及其权限ID。
User
has a permissions()
method that gets all the permissions for user 有一个permissions()
方法可获取用户的所有权限
public function permissions()
{
return $this->hasMany('App\ActionPermission');
}
checkUserPermissions
(middleware) checkUserPermissions
(中间件) public function handle($request, Closure $next)
{
$response = $next($request);
$userId = Auth::id();
$userPermissions = User::findOrFail($userId)->permissions()->get();
dd($userPermissions);
}
Since permissions()
is looking for user_id
key, and ActionPermission
model (table action_permission
) does not have the relevant user_id
key, I need the table users__action_permission
which holds he user_id
. 由于permissions()
正在寻找user_id
密钥,并且ActionPermission
模型(表action_permission
)没有相关的user_id
密钥,因此我需要表users__action_permission
来保存user_id
。
My question is if Laravel has a way for User::permissions()
to access users__action_permission
table, or do I need to build a model for that? 我的问题是Laravel是否可以通过User::permissions()
访问users__action_permission
表,还是我需要为此建立模型?
You do not need a model for the pivot table. 您不需要数据透视表的模型。
in User model add 在用户模型中添加
public function ActionPermissions() {
return $this->belongsToMany('App\User', 'users_action_permission');
}
in Action Permission model add 在动作权限模型中添加
public function Users() {
return $this->belongsToMany('App\ActionPermission', 'users_action_permission');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.