如何在ActiveRecord(Yii2)中设置多个字段的唯一性?我试过手写的
['a1', 'unique', 'targetAttribute' => ['a1', 'a2']]
Run Code Online (Sandbox Code Playgroud)
但它不起作用.
Nov*_*off 19
没有更长的相关性(它似乎是早期版本的Yii 2中的一个错误):
您应该使用attribute而不是targetAttribute
['a1', 'unique', 'attribute' => ['a1', 'a2']]
Run Code Online (Sandbox Code Playgroud)
在这种情况下,字段'a1'将收到错误消息.
而另一个案例:
[['a1', 'a2'], 'unique', 'attribute' => ['a1', 'a2']]
Run Code Online (Sandbox Code Playgroud)
现在'a1'和'a2'属性将收到错误消息,如果'a1'和'a2'不是唯一的.
正确:
来自docs(经过验证的工作示例)
// a1 needs to be unique
['a1', 'unique']
// a1 needs to be unique, but column a2 will be used to check the uniqueness of the a1 value
['a1', 'unique', 'targetAttribute' => 'a2']
// a1 and a2 need to be unique together, and they both will receive error message
[['a1', 'a2'], 'unique', 'targetAttribute' => ['a1', 'a2']]
// a1 and a2 need to be unique together, only a1 will receive error message
['a1', 'unique', 'targetAttribute' => ['a1', 'a2']]
// a1 needs to be unique by checking the uniqueness of both a2 and a3 (using a1 value)
['a1', 'unique', 'targetAttribute' => ['a2', 'a1' => 'a3']]
Run Code Online (Sandbox Code Playgroud)
targetAttribute将在最新的 yii2文档(2017)中使用
['a1', 'unique', 'targetAttribute' => ['a1', 'a2']]
Run Code Online (Sandbox Code Playgroud)
在这种情况下,字段“a1”将收到错误消息。
另一种情况:
[['a1', 'a2'], 'unique', 'targetAttribute' => ['a1', 'a2']]
Run Code Online (Sandbox Code Playgroud)
现在,如果“a1”和“a2”不是唯一的,“a1”和“a2”属性将收到错误消息。
comboNotUnique将使用自定义消息而不是message
[['a1', 'a2'], 'comboNotUnique' => 'Package Id already exist.', 'unique', 'attribute' => ['a1', 'a2']]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10516 次 |
| 最近记录: |