Laravel,独特的专栏

问题描述

我需要验证字段是否已经存在,引发错误,但是使用此代码不会触发错误

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->pais);
}),]
];
 $this->validate($request,$rules);

使用此代码,会引发此错误

 $rules = [
'depto' => [Rule::unique('departamento')->where(function ($query) use ($request) {
    return $query->where('departamento',]
];
$this->validate($request,$rules);

error

谢谢!

编辑:

不好,我需要检查两个字段,departamento和idPais,谢谢。

解决方法

这是由于您的字段名称而发生的。唯一规则将尝试查找该列名设置为请求值的记录(在您的情况下为depto,但您的列名为departamento)。自定义查询时,您不会覆盖它,而是在此默认行为的基础上添加。来自laravel docs

默认情况下,唯一规则将检查与要验证的属性名称匹配的列的唯一性。但是,您可以将不同的列名称作为唯一参数的第二个参数传递:

考虑到这一点,您可以更改唯一规则以将列设置为departamento而不是如下所示的depto,或更改发送departamento属性的请求,而不是depto

$rules = [
'depto' => [Rule::unique('departamento','departamento')->where(function ($query) use ($request) {
    return $query->where('idPais','=',$request->pais);
}),]
];

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...