Laravel Form Validator for Unique with hasMany Relationship

huangapple go评论55阅读模式
英文:

Laravel Form Validator for Unique with hasMany Relationship

问题

我遇到一个验证器错误,当尝试验证一个表单,其中一个 'user' 可以有多个 'emails' 时。目标是确保在更新 'user' 时,所有 'emails' 都是不同且唯一的,但在涉及两个或多个 'emails' 的编辑中,验证器会抛出错误,并不允许我继续添加或编辑 'user',因为它看到正在编辑的 'user' 上的 'emails',只有当 'user' 上有两个或更多 'emails' 时才会出现此情况。

这些 'emails' 存储在一个单独的表中,具有一个指向 'user' 的外键 'user_id',这些 'emails' 与之相关联。

以下是当前的规则代码:

$rules += [
    'user' => [
        'required',
        Rule::unique('users','name')->ignore($this->user),
    ],
    'emails.*' => [ 
        'distinct',                
        Rule::unique('emails','address')->ignore($this->user),
    ],
];

它会允许我在编辑或添加屏幕中向 'user' 添加第二个 'email',但尝试编辑包含两个或更多 'emails' 时,验证器会报错。

英文:

I am having a validator bug when try to validate a form where a 'user' can have many 'emails'. The goal is to make sure that when updating a 'user' the 'emails' all are distinct and unique, but on edits involving two or more 'emails' the validator throws and won't let me proceed with the addition or edit of the user because it sees the emails on the user I am editing, this is only the case when there are two or more 'emails' on the 'user'.

The emails are stored in a separate table with a foreign key 'user_id' that points it back to the user the emails are linked to.

Here is the current rule code

$rules += [
                'user' => [
                    'required',
                    Rule::unique('users','name')->ignore($this->user),
                    
                ],
                'emails.*' => [ 
                   'distinct',                
                    Rule::unique('emails','address')->ignore($this->user),
                ],
            ];

It will let me add a second 'email' to the user in the edit or add screens, but when trying to edit when there are two or more the validator throws.

答案1

得分: 0

你需要指定需要在电子邮件表中忽略的列名,尝试这样做:

Rule::unique('emails', 'address')->ignore($this->user->id, 'user_id')
英文:

You need to specify the name of the column that needs to be ignored in emails table, try this:

Rule::unique('emails','address')->ignore($this->user->id, 'user_id')

huangapple
  • 本文由 发表于 2023年3月31日 04:21:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/75892677.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定