首页 > 解决方案 > 在 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:从 userswhere user_id= 0 和(has= 角色)中选择计数(*)作为聚合)”

标签: phplaraveleloquentlaravel-validation

解决方案


我会用这个。这将解决您的问题,但我不知道是否是最好的方法。

    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.');
                }}
            ]

推荐阅读