Laravel,独特的列
Laravel, unique columns
我需要验证字段是否已经存在,抛出错误,但使用此代码不会触发任何错误
Laravel 7
table: departamento
column: id int incremental
column: departamento varchar(150)
column: idPais int
存储方法
$this->validate($request, ['departamento' => Rule::unique('departamento','idPais')->where('departamento',$request->depto)->where('idPais',$request->pais)]);
也试试这个
$rules = [
'depto' => [Rule::unique('departamento')->where(function ($query) use ($request) {
return $query->where('departamento','=', $request->depto)->where('idPais','=', $request->pais);
}),]
];
$this->validate($request,$rules);
使用此代码,抛出此错误
$rules = [
'depto' => [Rule::unique('departamento')->where(function ($query) use ($request) {
return $query->where('departamento','=', $request->depto)->where('idPais','=', $request->pais);
}),]
];
$this->validate($request,$rules);
谢谢!!!
编辑:
不好意思,我需要检查两个字段,departamento 和 idPais,谢谢。
发生这种情况是因为您的字段名称。唯一规则将尝试查找该列名设置为请求值的记录(在您的情况下,depto
,但您的列名是 departamento
)。当您自定义查询时,您并没有覆盖它,而是在此默认行为之上添加。来自 laravel docs:
By default, the unique rule will check the uniqueness of the column matching the name of the attribute being validated. However, you may pass a different column name as the second argument to the unique method:
考虑到这一点,您可以更改唯一规则以将列设置为 departamento
而不是 depto
,如下所示,或者更改发送 departamento
属性的请求而不是 depto
:
$rules = [
'depto' => [Rule::unique('departamento', 'departamento')->where(function ($query) use ($request) {
return $query->where('idPais','=', $request->pais);
}),]
];
我需要验证字段是否已经存在,抛出错误,但使用此代码不会触发任何错误
Laravel 7
table: departamento
column: id int incremental
column: departamento varchar(150)
column: idPais int
存储方法
$this->validate($request, ['departamento' => Rule::unique('departamento','idPais')->where('departamento',$request->depto)->where('idPais',$request->pais)]);
也试试这个
$rules = [
'depto' => [Rule::unique('departamento')->where(function ($query) use ($request) {
return $query->where('departamento','=', $request->depto)->where('idPais','=', $request->pais);
}),]
];
$this->validate($request,$rules);
使用此代码,抛出此错误
$rules = [
'depto' => [Rule::unique('departamento')->where(function ($query) use ($request) {
return $query->where('departamento','=', $request->depto)->where('idPais','=', $request->pais);
}),]
];
$this->validate($request,$rules);
谢谢!!!
编辑:
不好意思,我需要检查两个字段,departamento 和 idPais,谢谢。
发生这种情况是因为您的字段名称。唯一规则将尝试查找该列名设置为请求值的记录(在您的情况下,depto
,但您的列名是 departamento
)。当您自定义查询时,您并没有覆盖它,而是在此默认行为之上添加。来自 laravel docs:
By default, the unique rule will check the uniqueness of the column matching the name of the attribute being validated. However, you may pass a different column name as the second argument to the unique method:
考虑到这一点,您可以更改唯一规则以将列设置为 departamento
而不是 depto
,如下所示,或者更改发送 departamento
属性的请求而不是 depto
:
$rules = [
'depto' => [Rule::unique('departamento', 'departamento')->where(function ($query) use ($request) {
return $query->where('idPais','=', $request->pais);
}),]
];