問題描述
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'
這篇關于laravel 4:驗證唯一(數據庫)多個 where 子句的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!