在Laravel 4中如何添加联合唯一字段验证规则

4
我正在使用 Laravel 4.2 和 MySQL 数据库。 我有一个考试表,其中我正在录入考试并且字段为:id | examdate | batch | chapter | totalmarks。我在模式生成器中使用 $table->unique( array('examdate','batch','chapter') ); 创建了一个组合唯一键。现在我想要添加一个验证规则。我知道可以通过Laravel 唯一验证器规则 添加唯一验证,但问题是它只检查一个字段。我希望它可以将唯一性添加到这三个字段组合(用户不应能够添加具有相同的 examdate、batch 和 chapter 字段值组合的第二行)。在 Laravel 4 中是否可能做到呢?如果不可能,是否有任何变通方法?
2个回答

10

您可以编写自定义验证规则。该规则可能如下所示:

'unique_multiple:table,field1,field2,field3,...,fieldN'

那个代码看起来会像这样:

Validator::extend('unique_multiple', function ($attribute, $value, $parameters)
{
    // Get table name from first parameter
    $table = array_shift($parameters);

    // Build the query
    $query = DB::table($table);

    // Add the field conditions
    foreach ($parameters as $i => $field)
        $query->where($field, $value[$i]);

    // Validation result will be false if any rows match the combination
    return ($query->count() == 0);
});

您可以使用任意数量的字段作为条件,只需确保传递的值是包含与验证规则中声明的顺序相同的字段值的数组即可。因此,您的验证器代码应类似于以下内容:

$validator = Validator::make(
    // Validator data goes here
    array(
        'unique_fields' => array('examdate_value', 'batch_value', 'chapter_value')
    ),
    // Validator rules go here
    array(
        'unique_fields' => 'unique_multiple:exams,examdate,batch,chapter'
    )
);

这很棒 +1。我应该把这个类放在laravel 5.1的哪里? - Junior
@MikeA 请查看自定义验证规则文档 - Bogdan

0

对我来说它不起作用,所以我微调了一下代码。

Validator::extend('unique_multiple', function ($attribute, $value, $parameters, $validator)
{
     // Get the other fields
     $fields = $validator->getData();

     // Get table name from first parameter
     $table = array_shift($parameters);

    // Build the query
    $query = DB::table($table);

    // Add the field conditions
    foreach ($parameters as $i => $field) {
        $query->where($field, $fields[$field]);
    }

    // Validation result will be false if any rows match the combination
    return ($query->count() == 0);
 });

验证器看起来像这样。您不需要按照其他答案中所述的特定顺序列出DB表列名。
$validator = Validator::make($request->all(), [
        'attributeName' => 'unique_multiple:tableName,field[1],field[2],....,field[n]'
    ],[
        'unique_multiple' => 'This combination already exists.'
    ]);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接