我如何验证表格,如果privacy = public,则所有用户都拥有唯一的标题但privacy = private则每个用户都有一个唯一的标题。
---------------------------
user_id | title | privacy
---------------------------
2 | hello | public
---------------------------
2 | hello | private
---------------------------
2 | hello | private **Error**
---------------------------
2 | hello | public **Error**
---------------------------
3 | hello | public **Error**
---------------------------
3 | hello | private
---------------------------
答案 0 :(得分:1)
如果您想在Validator中执行
,可以使用此库url:https://github.com/felixkiss/uniquewith-validator
替代解决方案:
if($request->privacy == "private"){
$count = DB::table('your_table_name')
->where('title','=',$request->title)
->where('user_id','=,$request->user_id)
->count();
if($count >0){
return "You error message for privacy private"
}
}else{
$count = DB::table('your_table_name')
->where('title','=',$request->title)
->count();
if($count >0){
return "You error message for privacy public"
}
}
希望你能理解这个简单的代码。问是否有任何疑问。
答案 1 :(得分:1)
您需要一个自定义验证器,基本上将使用基于隐私条件的内置唯一规则:
class CustomValidator extends Illuminate\Validation\Validator
{
public function validateUniqueIfPrivacy($attribute, $value, $parameters) {
$privacyValue = array_get($validator->getData(), 'privacy_field');
if ($privacyValue == 'private' ) {
return $isTitleUniqueForUser = $this->validateUnique($attribute, $value, 'my_table', 'title', NULL, 'user_id', $parameters[0]);
} else {
return $isTitleUniqueForAll = $this->validateUnique($attribute, $value, 'my_table', 'title');
}
}
}
注册自定义验证器并自动加载其类后,您可以像这样使用它,只传递$userId
作为参数:
$rules = array(
'title' => 'unique_if_privacy:,' . $user->id,
);
有关如何实施自定义验证器的更多信息:Laravel 4.2 documentation(也适用于Laravel 5)
答案 2 :(得分:0)
嘿,经过大量的尝试,我可以解决我的问题! 谢谢每个帮助我或建议我的人
主要是我自己的解决方案
'title' => Rule::unique('galleries')->where(function ($query)
{
if($this->input('privacy')=='private')
{
$query->where([['privacy','=','private'],['user_id','=',Auth::user()->id]]);
}
else
$query->where('privacy', '=','public');
}),
希望这是最简单的解决方案