如何在ActiveRecord(Yii2)中设置多个字段的唯一性?

alm*_*one 15 yii2

如何在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适用于我..属性生成错误. (5认同)
  • 我觉得有些事情不可能就在这里.Docs说`$ attributes`*要由此验证器*验证的属性.和`$ targetAttribute`*应该用于验证当前属性值的唯一性***的ActiveRecord属性的名称.**所以,`$ targetAttribute`应该可以正常工作(事实上,它对我来说工作正常).甚至自己的Yii2文档示例也使用`targetAttribute`. (3认同)

Kul*_*ngi 6

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)