问题描述
我正在使用 Laravel 4.2 和 mysql db.
我有一个考试表,我正在其中参加考试,字段是 --> id |考试日期 |批次 |章节 |总分
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 个字段添加唯一性(用户不能添加具有相同值组合的考试日期、批次和章节字段的第二行).
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 中添加组合的唯一字段验证器规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!