如何在Laravel 4中添加组合的唯一字段验证器规则 [英] How to add combined unique fields validator rule in Laravel 4

查看:81
本文介绍了如何在Laravel 4中添加组合的唯一字段验证器规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Laravel 4.2和mysql db.
我有一张考试表,我在其中参加考试,字段为->
id | examdate | batch | chapter | totalmarks

I am using Laravel 4.2 and mysql db .
I have an exam table in which i am taking Exams entry and the fields are -->
id | examdate | batch | chapter | totalmarks

我已经在架构生成器中使用
$table->unique( array('examdate','batch','chapter') );组合了唯一键.
现在我想向其添加验证规则.我知道我可以通过 laravel唯一验证器规则添加唯一验证,但是问题是,它只检查一个字段.
我希望它为组合的3个字段添加唯一性(用户必须不能添加具有相同值的ExcelATEDATE,Batch和Chapter字段的第二行).

I have made a combined unique key using
$table->unique( array('examdate','batch','chapter') ); in schema builder.
Now I want to add a validation rule to it. I know i can add unique validation by laravel unique validator rule but the problem is ,it checks only for one field .
I want it to add uniqueness to the 3 fields combined(user must not be able to add second row with same value combination of examdate,batch and chapter fields).

在laravel 4中甚至可以做到这一点.是否有任何解决方法?

Is it even possible to do it in laravel 4 .Is there any workaround if its not possible?

推荐答案

您可以编写自定义验证程序规则.规则可能看起来像这样:

You could write a custom validator rule. The rule could look something like this:

'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);
});

您可以根据需要使用任意多个字段,只需确保传递的值是一个包含字段值的数组,该数组的值与验证规则中声明的顺序相同.因此,您的验证器代码将如下所示:

You can use as many fields as you like for the condition, just make sure the value passed is an array containing the values of the fields in the same order as declared in the validation rule. So your validator code would look something like this:

$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'
    )
);

这篇关于如何在Laravel 4中添加组合的唯一字段验证器规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆