首页 文章

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

提问于
浏览
4

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

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

是否有可能在laravel 4中进行 . 如果不可能,有任何解决方法吗?

2 回答

  • 9

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

    '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'
        )
    );
    
  • 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.'
        ]);
    

相关问题