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


Waht's the best way to use unique validation according to an attribute in a table

我正在使用Laravel 5.1,我有一个模型客户,它有很多车辆。我像这样设置车辆模型的验证:

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

到目前为止,一切都很好:我不能插入两辆具有相同代码或登记号的车辆。
我想做的是:
我可以设置自定义验证,允许我仅为给定的CustumerID插入唯一代码或注册号值吗?

例:

客户 1 :
车辆 1:代码 1,登记号 1
车辆 2:代码 2,注册号 2

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

客户 2 :
车辆 1:代码 1,登记号 1
车辆 2:代码 5,登记号 5

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

请问有什么想法吗?

只要客户 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)

语法

 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否则它会影响用户体验