【问题标题】:How to add combined unique fields validator rule in Laravel 4如何在 Laravel 4 中添加组合的唯一字段验证器规则
【发布时间】:2014-12-28 07:26:34
【问题描述】:

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

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

甚至可以在 laravel 4 中做到这一点。如果不可能的话,有什么解决方法吗?

【问题讨论】:

    标签: mysql validation laravel laravel-4


    【解决方案1】:

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

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

    【讨论】:

    【解决方案2】:

    它对我不起作用,所以我稍微调整了代码。

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

    验证器如下所示。您不需要其他答案中所述的特定顺序的数据库表列名。

    $validator = Validator::make($request->all(), [
            'attributeName' => 'unique_multiple:tableName,field[1],field[2],....,field[n]'
        ],[
            'unique_multiple' => 'This combination already exists.'
        ]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-15
      • 1970-01-01
      • 1970-01-01
      • 2015-02-27
      • 2019-07-12
      • 1970-01-01
      • 2015-02-03
      • 2018-05-24
      相关资源
      最近更新 更多