更新
我有一个包含以下列的表:
- ID
- production_year
- type
如果type
已经与用户想要传递的值一起存在于表中,请检查production_year
是否也已经存在,但仅当这些值存在于同一记录中时,验证才会失败。否则,让用户存储此记录。
我试图检查同一记录中几个字段的唯一性。。。
我看过关于条件验证的文档,但没有找到答案。
代码
public function rules()
{
return [
// I'd like to check the uniqueness of both of them. In the same record
'production_y' => 'required|unique',
'fk_type' => 'required|unique',
];
}
知道吗?谢谢
Laravel 5.3更新:
现在,您可以使用rule('Illuminate'Validation'Rule
(类流畅地生成相同的规则。
不再需要字符串方式的NULL,id
部分参见:
public function rules()
{
$type = $this->get('fk_type');
return [
'production_y' => [
'required',
Rule::unique('your_table', 'production_year')->where(function($query) {
$query->where('type', $type);
}),
],
];
}
原始答案
现在无法测试,你能试试吗:
public function rules()
{
$type = $this->get('fk_type');
return [
'production_y' => "required|unique:your_table,production_year,NULL,id,type,{$type}",
// ...
];
}
解释:
unique:your_table
为唯一性检查设置表格,production_year
这与production_y
匹配,NULL,id
检查所有记录。3.1.如果你像
{$id},id
一样使用,它将检查除了带有{$id}
、的记录之外的唯一性,type,{$type}
,类型应为{$type}
这将产生类似的东西(不是确切的查询,只是为了表达想法(:
select count(*) from your_table where production_year = $product_y and where type = $type and where id <> null
如果有人从laravel 8中客串,我试过了,它成功了!!对我来说,我需要检查(category_id,subcategory_d(的唯一性,这意味着你可以找到(1,2(、(1,3(、!!
'category' => "required|unique:tickets,category_id,NULL,id,subcategory_id,{$request->input('subcategory')}"