我有一个站点,它有多个实例(公司)。
每个公司都可以添加自己的库存,并且unit
编号在实例(公司)中必须是唯一的。但我想允许每个公司都有相同的单元号。因此,unit+ instance_id
需要是唯一的。有没有一种方法可以实现这种签入请求规则?
以下规则检查库存中是否已存在单元。我需要添加inventory.id AND inventory_instance_id
的检查
public function rules() {
return [
'unit' => 'unique:inventory|required|max:45',
'comments' => 'sometimes|max:255'
];
}
public function messages() {
return [
'unit.unique' => 'Unit number already exists!',
'unit.required' => 'Enter Unit Number!',
'max' => ':attribute - Should not be longer than 255 symbols!'
];
}
unique
验证允许使用许多参数。语法大致为unique:table,column,except,idColumn,whereN,valueN
。
第一个参数是表,第二个是要唯一的字段,第三个是要忽略的id,第四个是第三个参数的id列,然后第四个和第五个(以及6/第七个等)允许您为唯一验证指定其他where子句。这就是你想要的。
您可以使用第四个和第五个参数来指定您的单元在指定的实例id中必须是唯一的。假设您的实例id存储在inventory.instance_id
中,并且该字段的值位于一个名为$instanceId
的变量中,则您的规则看起来像:
public function rules() {
$instanceId = 1;
return [
'unit' => 'unique:inventory,unit,NULL,id,instance_id,'.$instanceId.'|required|max:45',
'comments' => 'sometimes|max:255'
];
}
正如您可能已经猜到的,您现在的问题之一是您的规则是动态生成的。您需要找到一种方法,用您正在检查的实例id更新您的规则。
检查此包:https://github.com/felixkiss/uniquewith-validator
我认为它解决了你的问题。