【问题标题】:Laravel 4: Unique Validation for Multiple ColumnsLaravel 4:多列的唯一验证
【发布时间】:2014-08-08 10:46:24
【问题描述】:

我知道之前有人问过这个问题,但我没有得到相关答案。

我想知道如何编写规则来检查两列的唯一性。我曾尝试编写如下规则:

public $rules = array(
    "event_id"=>"required",
    "label"=>"required|unique:tblSection,label,event_id,$this->event_id",
    "description"=>"required"
);

在我的示例中,我需要进行验证,以便一个标签对于单个事件 ID 是唯一的,但也可以用于其他事件 ID。例如我想实现:

id   event_id    label   description
1     1          demo    testing
2     2          demo    testing

在上面定义的规则中,我需要以某种方式传递当前选定的 event_id,以便它可以检查数据库表中是否不存在选定 event_id 的标签,但我收到如下语法错误:

{"error":{"type":"Symfony\\Component\\Debug\\Exception\\FatalErrorException","message":"syntax error, unexpected '\"'","file":"\/var\/www\/tamvote\/app\/modules\/sections\/models\/Sections.php","line":39}}

注意:我不想使用任何包,只想检查 laravel 4 是否足以允许编写此类规则。

【问题讨论】:

    标签: validation laravel-4 unique multiple-columns


    【解决方案1】:

    正如你我一直在寻找几个小时来做​​这件事但没有任何效果,我测试了所有东西......突然间我遇到了这个文档的随机性:

    'email' => Rule::unique('users')->where(function ($query) {
                  return $query->where('account_id', 1);
               })
    

    https://laravel.com/docs/5.5/validation#rule-unique

    它工作得很好,而且非常灵活:)

    【讨论】:

      【解决方案2】:

      就像提到的Sabrina Leggett 一样,您需要创建自己的自定义验证器。

      Validator::extend('uniqueEventLabel', function ($attribute, $value, $parameters, $validator) {
          $count = DB::table('table_name')->where('event_id', $value)
                                          ->where('label', $parameters[0])
                                          ->count();
      
          return $count === 0;
      }, 'Your error message if validation fails.');
      

      您可以通过在规则中添加以下行来调用您的验证器:

      'event_id' => "uniqueEventLabel:".request("label")
      

      如果需要更多字段,可以在 sql 语句中添加新的 where 子句。

      (来源:edcs 来自this answer

      【讨论】:

        【解决方案3】:

        如果您想静态声明您的验证规则,您也可以这样做。这不是最有效的,因为它会检查数据库中的每个值。

        protected $rules = [
            'user_id' => 'unique_multiple:memberships,user_id,group_id',
            'group_id' => 'unique_multiple:memberships,user_id,group_id',
        ]
        
        /**
         * Validates that two or more fields are unique
         */
        Validator::extend('unique_multiple', function ($attribute, $value, $parameters, $validator)
        {
            //if this is for an update then don't validate
            //todo: this might be an issue if we allow people to "update" one of the columns..but currently these are getting set on create only
            if (isset($validator->getData()['id'])) return true;
        
            // 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, $validator->getData()[$field]);
            }
        
            // Validation result will be false if any rows match the combination
            return ($query->count() == 0);
        
        });
        

        【讨论】:

          【解决方案4】:

          Mohamed Bouallegue 的回答是正确的。

          在您的控制器中为您执行的 store 方法:

          Model::$rules['label'] = 'required|unique:table_name,label,NULL,event_id,event_id,' .$data['event_id'];
          

          其中 $data 是您的 POST 数据。

          对于您执行的 update 方法:

          $model = Model::find($id);
          Model::$rules['label'] = 'required|unique:table_name,label,NULL,event_id,event_id,'.$data['event_id'].',id,id'.$model->id;
          

          其中 $data 是您的 PUT/PATCH 数据,$model 是您正在编辑的记录,id 是表主键。

          【讨论】:

            【解决方案5】:

            我之前没有尝试过,但我认为如果您在验证之前获得 event_Id,那么您可以这样做:

            'label' => 'unique:table_name,label,NULL,event_id,event_id,'.$eventId
            //you should get the $eventId first
            

            【讨论】:

            • 它会产生一个错误 "{"error":{"type":"Symfony\\Component\\Debug\\Exception\\FatalErrorException","message":"syntax error, unexpected '. ', 期待 ')'","file":"\/var\/www\/tamvote\/app\/modules\/sections\/models\/Sections.php","line":40}}"
            • 我怎样才能先得到 eventid,因为上面的语句将被写入 $rules 数组,它只是模型中的一个公共变量。
            • 如果您在控制器中创建规则数组,那么您可以获得 event_id 并将其连接到规则
            猜你喜欢
            • 2014-12-16
            • 2018-10-25
            • 2021-04-28
            • 2013-08-30
            • 1970-01-01
            • 2018-04-28
            • 1970-01-01
            • 2014-03-14
            相关资源
            最近更新 更多