Laravel 4:多列的唯一验证 [英] Laravel 4: Unique Validation for Multiple Columns

查看:80
本文介绍了Laravel 4:多列的唯一验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个问题已经提过,但是我没有得到相关的答案.

I know this question has been asked earlier but i did not get relevant answer.

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

I want to know that how can i write a rule to check uniqueness of two columns. I have tried to write a rule like:

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

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

In my example i need to put validation so that one label could be unique for a single event id but may be used for other event id as well. For Example i want to achieve:

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

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

In the rule defined above, somehow i need to pass current selected event_id so that it could check whether the label does not exist in the database table for selected event_id but i am getting syntax error like:

{"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是否具有足够的能力来编写此类规则.

Note: I don't want to use any package but simply checking if laravel 4 capable enough to allow to write such rules.

推荐答案

穆罕默德·布阿里格(Mohamed Bouallegue)的答案是正确的.

The answer from Mohamed Bouallegue is correct.

在用于 store 方法的控制器中,您可以执行以下操作:

In your controller for the store method you do:

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

其中$ data是您的POST数据.

where $data is your POST data.

对于更新方法,您可以执行以下操作:

And for the update method you do:

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

where $data is your PUT/PATCH data, $model is the record you are editing and id is the table primary key.

这篇关于Laravel 4:多列的唯一验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆