laravel 4:验证唯一(数据库)多个 where 子句

2021-12-26 00:00:00 validation sql php laravel eloquent

laravel 4 文档提到了独特的字段验证.他们在这里解释了如何将 where 子句包含到唯一验证中.唯一表的单个 WHERE 子句,例如:

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:

$validator = Validator::make(
    array(
        'name' => 'John Doe'
    ),
    array(
        'name' => 'unique:table,field,NULL,id,field1,value1'
    )
);

  • http://laravel.com/docs/validation#rule-unique
  • 现在我假设这会执行以下操作:

    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.

    所以我想知道是否有办法添加更多 where 子句?如果是这样怎么办?

    So i was wondering if there was a way to add more where clauses? And if so how?

    推荐答案

    我原来的问题结束:

    我可以将它们堆叠起来,或者如果没有,我必须如何编写验证?所以我可以添加,field2,value2,field3,value3"等.并将它们堆叠起来像这样吗?

    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?

    回答

    是的,我可以像下面那样堆叠它们.因此,如果我想向我的唯一验证器添加多个 where 子句,我会这样做:

    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:

    'name' => 'unique:table,field,NULL,id,field1,value1,field2,value2,field3,value3'
    


    例外

    根据 Laravel 文档

    The third parameter given in the unique rule is the except parameter, according to the Laravel documentation.

    unique:table,column,except,idColumn
    

    我将此参数保留为 NULL,因为它与原始问题无关.想知道这个NULL在唯一规则中的作用是什么的,让我详细说明一下:

    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:

    except 参数强制一个唯一的规则忽略给定的 ID.因此,将其指定为 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 为 1.那么我们在创建新用户时可以做的是:

    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:

    'name' => 'unique:users,email,1,id'
    

相关文章