php - 在 Laravel 验证规则“存在”中使用模型关系
问题描述
数据库架构
users
-id
-name
-email
...
roles
-id
-name
用户可能有多个角色,反之亦然(我已经在模型中定义了关系)
数据透视表
role_user
-id
-user_id
-role_id
试图制定的验证规则:user_id 必须存在于 users 表中并且角色 id = 4
//...
'user_id' => ['nullable', Rule::exists('users')->where(
function ($query) {
$query->whereHas('roles',
function ($q) {
$q->where('id', 4);
}
);
}
)],
//...
错误消息:“SQLSTATE [42S22]:找不到列:1054 'where 子句'中的未知列'有'(SQL:从
users
whereuser_id
= 0 和(has
= 角色)中选择计数(*)作为聚合)”
解决方案
我会用这个。这将解决您的问题,但我不知道是否是最好的方法。
use Validator; // on the top
$validator = Validator::make($request->all(), [
'user_id' => 'nullable|numeric|exists:users,id',
]);
if ($validator->fails()) {
return response()->json($validator->errors(), 422);
}
$user = User::find($request->user_id);
if(!$user || !$user->roles->first() || $user->roles->first()->id != 4) {
return response()->json(['user_id'=>['You dont have permission.']], 422);
}
您可以尝试的另一种方法
'user_id' => [
'nullable',
'numeric',
'exists:users,id',
function ($attribute, $value, $fail) {
$editorsIDs = User::whereHas('roles', function ($q) {
$q->where('id', 4);
})->pluck('id');
if(! $editorsIDs->contains($value)) {
$fail('You dont have permission.');
}}
]
推荐阅读
- php - 如何使用 Ajax 和 PHP 上传文件(有/无其他表单数据)?
- node.js - 从节点 js 连接到 postgresql
- django - 如何根据相关字段在 django 过滤对象?
- python - Numpy图像数组根据二进制类别设置像素维度值
- json - 在数据库中有 JSON 列时存储 PK Id 或名称?
- python-3.x - 在类实例的方法中修补变量
- python-3.x - Python OOP 继承
- javascript - 在组件内向左滚动的方式是什么?
- apache - 如何强制 apache 使用绝对寻址?
- apache-kafka - Kafka:使消费者组处于非活动状态