Laravel 4:多列的独特验证

问题描述 投票:8回答:5

我知道这个问题早先被问过,但我没有得到相关答案。

我想知道如何编写规则来检查两列的唯一性。我试过写一个像这样的规则:

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
5个回答
8
投票

Mohamed Bouallegue的答案是正确的。

在您的控制器中,您可以执行以下操作:

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

其中$ data是你的POST数据。

对于更新方法,您可以:

$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是表主键。


2
投票

我以前没试过这个,但我想如果你在验证之前得到event_Id那么你可以这样做:

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

2
投票

如果要静态声明验证规则,也可以执行此操作。它不是最有效的,因为它检查数据库中的每个值。

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

});

0
投票

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子句。

(来源:edcsthis answer


0
投票

因为我正在寻找几个小时才能做到这一点,但没有任何效果,我测试了所有内容......我突然发现文档的随机性:

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

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

它完美无缺,而且非常灵活:)

© www.soinside.com 2019 - 2024. All rights reserved.