我正在使用Laravel 4编写一个用户注册表单,该表单允许用户在first_name
和last_name
字段中输入自己的姓名。在表单输入验证过程中,我想根据要保存的表中的值中的组合名称first_name + " " + last_name
来检查这两个字段的唯一性。
我知道您可以使用unique
规则检查单个字段的唯一性,甚至可以通过指定unique:tableName,fieldName
来覆盖该字段。
理想情况下,我会做一些类似unique:tableName,first_name + " " + last_name
的事情,或者在模型本身中指定一些东西,但我在复合/虚拟字段上找不到任何东西。
编写自己的规则。它可以看起来像这样:
'unique_composite:table,field1,field2,field3,...,fieldN'
在表名之后枚举的字段将被连接起来,并根据组合值进行检查。验证规则如下所示:
Validator::extend('unique_composite', function ($attribute, $value, $parameters)
{
// Get table name from first parameter
$table = array_shift($parameters);
$fields = implode(',', $parameters);
// Build the query that searches the database for matches
$matches = DB::table($table)
->where(DB::raw('CONCAT_WS(" ", ' . $fields . ')'), $value)
->count();
// Validation result will be false if any rows match the combination
return ($matches == 0);
});
在你的验证器中,你可以有这样的东西:
$validator = Validator::make(
array('full_name' => $firstName + ' ' + $lastName),
array('full_name' => 'unique_composite:users,first_name,last_name')
);
使用此规则,您可以使用任意数量的字段,而不仅仅是两个。
我最终扩展了Validator类来定义自定义验证器规则。我在应用程序的first_name
字段中检查它,主要是因为我不想在生成全名时做额外的工作。除了在考虑了这个问题后没有必要将其设置为复合值之外,我只是将其设置成检查指定字段的所有值的AND
。您可以指定任意数量的字段,如果其中一个字段不存在于验证器数据中,则会引发异常。我甚至不确定这是否可以单独使用现有的unique
规则来实现,但无论如何,这都是一个很好的练习。
'first_name' => 'unique_multiple_fields:members,first_name,last_name'
我的验证器子类代码:
use IlluminateValidationValidator as IlluminateValidator;
class CustomValidatorRules extends IlluminateValidator
{
/**
* Validate that there are no records in the specified table which match all of the
* data values in the specified fields. Returns true iff the number of matching
* records is zero.
*/
protected function validateUniqueMultipleFields( $attribute, $value, $parameters )
{
if (is_null($parameters) || empty($parameters)) {
throw new InvalidArgumentException('Expected $parameters to be a non-empty array.');
}
if (count($parameters) < 3) {
throw new InvalidArgumentException('The $parameters option should have at least 3 items: table, field1, field2, [...], fieldN.');
}
// Get table name from first parameter, now left solely with field names.
$table = array_shift($parameters);
// Uppercase the table name, remove the 's' at the end if it exists
// to get the class name of the model (by Laravel convention).
$modelName = preg_replace("/^(.*)([s])$/", "$1", ucfirst($table));
// Create the SQL, start by getting only the fields specified in parameters
$select = $modelName::select($parameters);
// Generate the WHERE clauses of the SQL query.
foreach ($parameters as $fieldName) {
$curFieldVal = ($fieldName === $attribute) ? $value : $this->data[$fieldName];
if (is_null($curFieldVal)) {
// There is no data for the field specified, so fail.
throw new Exception("Expected `{$fieldName}` data to be set in the validator.");
}
// Add the current field name and value
$select->where($fieldName, '=', $curFieldVal);
}
// Get the number of fields found
$numFound = $select->count();
return ($numFound === 0);
}
}
如果你好奇的话,我确实使用了我最初研究的复合方法来实现它。代码如下。事实证明,"分隔符"完全没有意义,因此我最终将其重构为使用上面指定的多字段方法。
use IlluminateValidationValidator as IlluminateValidator;
class CustomValidatorRules extends IlluminateValidator
{
/**
* Validate that the final value of a set of fields - joined by an optional separator -
* doesn't match any records in the specified table. Returns true iff the number of
* matching records is zero.
*/
protected function validateUniqueComposite( $attribute, $value, $parameters )
{
if (is_null($parameters) || empty($parameters)) {
throw new InvalidArgumentException('Expected $parameters to be a non-empty array.');
}
if (count($parameters) < 3) {
throw new InvalidArgumentException('The $parameters option should have at least 3 items: table, field1, field2, [...], fieldN.');//, [separator].');
}
// Get table name from first parameter
$table = array_shift($parameters);
// Determine the separator
$separator = '';
$lastParam = array_pop($parameters);
if (! isset($this->data[$lastParam])) {
$separator = $lastParam;
}
// Get the names of the rest of the fields.
$fields = array();
foreach ($parameters as $fieldName) {
array_push($fields, $table . "." . $fieldName);
}
$fields = implode(', ', $fields);
$dataFieldValues = array();
foreach ($parameters as $fieldName) {
$curFieldVal = ($fieldName === $attribute) ? $value : $this->data[$fieldName];
if (is_null($curFieldVal)) {
throw new Exception("Expected `{$fieldName}` data.");
}
array_push($dataFieldValues, $curFieldVal);
}
$compositeValue = implode($separator, $dataFieldValues);
// Uppercase the table name, remove the 's' at the end if it exists
// to get the class name of the model (by Laravel convention).
$modelName = preg_replace("/^(.*)([s])$/", "$1", ucfirst($table));
$raw = DB::raw("concat_ws('" . $separator . "', " . $fields . ")");
$model = new $modelName;
// Generate the SQL query
$select = $modelName::where($raw, '=', $compositeValue);
$numFound = $select->count();
return ($numFound === 0);
}
}
在不创建自定义验证器的情况下,您还可以指定更多将添加为"其中";子句到查询和do:
'first_name' => 'required|unique:table_name,first_name,null,id,last_name,'.$data['last_name'],
'last_name' => 'required|unique:table_name,last_name,null,id,first_name,'.$data['first_name'],
这样,first_name
的唯一性将仅在last_name
等于输入的last_name
(在我们的示例中为$data['last_name']
)的行上强制执行。
CCD_ 14的唯一性也是如此。
如果您想强制唯一规则忽略给定的ID,只需将null
替换为该特定的ID即可。
参考:http://laravel.com/docs/4.2/validation#rule-唯一