【问题标题】:Laravel Getting sql error when trying to give unique field validationLaravel 尝试提供唯一字段验证时出现 sql 错误
【发布时间】:2020-10-03 09:54:25
【问题描述】:

这是来自我用于标签表单验证的验证

public function rules()
{
     return [
         'name' => 'required|max:50|min:3|unique:tags,name,'.$this->tag,
     ];
}

我的控制器代码

public function update(TagValidation $request, Tag $tag )
{
    $tag->update($request->all());
}

我试图在尝试更新时避免唯一字段验证问题。使用后

unique:tags,name,'.$this->tag

我遇到了 sql 错误

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'name:"abc"' in 'where clause' (SQL: select count(*) as aggregate from `tags` where `name` = abc and `name:"abc"` <> {"id":14 and `created_at:"2020-06-13T16:24:36`.`000000Z"` = updated_at:"2020-06-13T16:46:44.000000Z"}) 

但我在数据库中有 name 列,如果我在验证中不使用 $this->tag,存储工作正常。

【问题讨论】:

  • 我假设您想在使用 $this-&gt;tag 时将某个字段的值传递给规则(可能是模型的 id),而不是模型实例本身?
  • 如果我使用 $this->id ,我会收到“名称已被占用。”
  • $this-&gt;tag 是一个模型实例...您正在将模型实例连接到您正在构建的字符串(序列化模型),而不是像那里的 id 那样传递单个值... @ 987654328@ 将是标签的 id
  • 使用 $this->tag->id 后,我收到验证错误“名称已被占用。”看到这个 ans stackoverflow.com/questions/23587833/… 后,我使用了模型实例。
  • 我的路线是 tags/14/edit

标签: laravel laravel-7.x


【解决方案1】:

您应该传递要忽略的唯一规则的记录的 id,我认为该规则是该标签:

 'name' => 'required|max:50|min:3|unique:tags,name,'. $this->tag->id,

或者您可以使用规则的对象版本,您可以直接将模型传递给:

'name' => [
    'required', 'max:50', 'min:3', 
    Rule::unique('tags')->ignore($this->tag),
],

【讨论】:

    【解决方案2】:

    小心,因为唯一验证是

    unique:table,column,except,idColumn

    您正在传递标签的值 anme 但不是必需的

    你实际使用:

    return [
       'name' => 'required|max:50|min:3|unique:tags,name,'.$this->tag,
    ];
    

    但您需要使用它,我向您展示了在存储和更新(POST 和 PUT 方法)上使用相同验证的工作示例:

    public function rules()
    {
        if ($this->method() == 'PUT') 
        {
            return [
                 'name' => 'required|unique:tags,name,'.$this->id.',id',
            ];
        }elseif ($this->method() == 'POST'){
             return [
                 'name' => 'required|unique:tags,name'
             ];
        }
    }
    

    包含在 Laravel 7* 上,您可以直接使用模型

    public function rules()
    {
        // Check Create or Update
        if ($this->method() == 'PUT') 
        {
            return [
                'name' => 'required|unique:App\Tag,name,'.$this->id.',id'
            ];
        }elseif ($this->method() == 'POST'){
            return [
                'name' => 'required|unique:App\Tag,name'
            ];
        }
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-24
    • 1970-01-01
    • 2018-11-03
    • 1970-01-01
    • 2018-08-09
    • 2020-07-07
    • 1970-01-01
    • 2021-01-12
    相关资源
    最近更新 更多