Waht是根据表中的属性使用唯一验证的最佳方式

时间:2016-01-21 18:06:23

标签: php validation laravel unique laravel-5.1

我使用的是Laravel 5.1,我是一个拥有众多车辆的模型客户。 我为Vehicle模型设置了这样的验证:

public static $Rules = array(
    'code' => 'required|unique:vehicles', 
    'registernumber' => 'required|unique:vehicles'                       
);

到目前为止,一切都很好:我无法插入两辆代码相同或注册的车辆。
我想做的是:
我是否可以设置自定义验证,允许我为给定的CustumerID插入唯一代码或registernumber值?

示例:

  

客户1:
        Vehicle1:code1,registernumber1
        Vehicle2:code2,registernumber2

  (Here I can't insert for example two codes having 'code1' value with Customer1)
  

客户2:
        Vehicle1:code1,registernumber1
        Vehicle2:code5,registernumber5

  (Here I can't insert for example two registernumbers having 'registernumber5' value with Customer2)

请问好吗?

2 个答案:

答案 0 :(得分:0)

语法

 ALTER TABLE `tablename`
 ADD UNIQUE KEY `my_unique_key` (`colname1`, `colname2`);

在你的例子中

 ALTER TABLE `yourtable`
 ADD UNIQUE KEY `unique_reg` (`customername`, `vehicle`, `code`, `regno`);

尝试此操作,但您应该处理db_error,否则会影响用户体验

答案 1 :(得分:0)

只要客户ID在该表中。 unique验证规则的工作方式如下:

unique:
    [table name, optionally with a connection name],
    [the column you are checking for uniqueness, optional],
    [the id of the row that will be ignored in the check (for example if you are updating a row, you want the row you are updating to not be included), optional],
    [the column name that contains the id you are running the check against, optional],
    [additional where clauses (where_column, where_value)]

因此,如果您的表架构如下所示:

vehicle_id, code_number, registration_number, customer_id

您只想对同一客户的行运行唯一检查,您可以这样做:

$customer_id = 'whatever';

$Rules = array(
    'code' => 'required|unique:vehicles,code_number,NULL,vehicle_id,customer_id,'.$customer_id                     
); 

这将仅对行where('customer_id', $customer_id)

运行检查