我最终扩展了 Validator 类来定义自定义验证器规则。我在我的应用程序的first_name 字段中检查它,主要是因为我不想在生成全名时做额外的工作。除了没有将其设为复合值(考虑到问题后没有必要这样做),我只是将其设置为检查指定字段的所有值的AND。您可以指定任意数量的字段,如果其中一个不存在于验证器数据中,它将引发异常。我什至不确定这是否可以仅使用现有的 unique 规则来完成,但无论如何这是一个很好的练习。
'first_name' => 'unique_multiple_fields:members,first_name,last_name'
我的验证器子类代码:
use Illuminate\Validation\Validator 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 Illuminate\Validation\Validator 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);
}
}