laravel 4:验证唯一(数据库)多个 where 子句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19377069/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
laravel 4: validation unique (database) multiple where clauses
提问by rofavadeka
The laravel 4 documentation mentions unique field validation. They explain here how to include where clauses to the unique validation. A single WHERE clause for the unique table for example:
laravel 4 文档提到了独特的字段验证。他们在这里解释了如何将 where 子句包含到唯一验证中。唯一表的单个 WHERE 子句,例如:
$validator = Validator::make(
array(
'name' => 'John Doe'
),
array(
'name' => 'unique:table,field,NULL,id,field1,value1'
)
);
Now i assume this does something like:
现在我假设这会做类似的事情:
"SELECT id FROM table WHERE field = 'John Doe' AND field1 = value1 LIMIT 1"
Then check's if this query returns a result and if not passes the validator.
然后检查此查询是否返回结果,如果没有通过验证器。
So i was wondering if there was a way to add more where clauses? And if so how?
所以我想知道是否有办法添加更多 where 子句?如果是这样怎么办?
回答by rofavadeka
Ending of my original question:
结束我的原始问题:
Can i just stack them or how do i have to write my validation if not? So can i just add ",field2,value2,field3,value3" ect. and stack them like this?
我可以将它们堆叠起来,或者如果没有,我该如何编写验证?所以我可以添加“,field2,value2,field3,value3”等。并像这样堆叠它们?
Answer
回答
Yes i can just stack them like below. So if i would like to add multiple where clauses to my unique validator i would do it like this:
是的,我可以像下面那样堆叠它们。因此,如果我想向我的唯一验证器添加多个 where 子句,我会这样做:
'name' => 'unique:table,field,NULL,id,field1,value1,field2,value2,field3,value3'
Exceptions
例外
The third parameter given in the unique rule is the except parameter, according to the Laravel documentation.
根据Laravel 文档,唯一规则中给出的第三个参数是 except 参数。
unique:table,column,except,idColumn
I left this parameter NULL because it is not that relevant to the original question. For those who would like to know what the function of this NULL is within the unique rule, let me elaborate:
我将此参数保留为 NULL,因为它与原始问题无关。对于那些想知道这个 NULL 在唯一规则中的功能的人,让我详细说明:
The except parameter forces a unique rule to ignore a given ID. So specifying it as a NULL will result in checking against every record ( i.e. ignoring nothing ).
除了参数强制唯一规则忽略给定的 ID。因此,将其指定为 NULL 将导致检查每条记录(即不忽略任何内容)。
For example:Let's say we want our user email to be unique but our admin user might also have a normal user account with the same email. Assuming our admin user is the first user we created it has the id of 1. So what we could do when creating new users is:
例如:假设我们希望我们的用户电子邮件是唯一的,但我们的管理员用户可能也有一个使用相同电子邮件的普通用户帐户。假设我们的 admin 用户是我们创建的第一个用户,它的 id 为 1。那么我们在创建新用户时可以做的是:
'name' => 'unique:users,email,1,id'