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

如何在ActiveRecord(Yii2)中设置多个字段的唯一性?,yii2,Yii2,如何在ActiveRecord(Yii2)中设置多个字段的唯一性? 我已经按照手册上写的那样试过了 ['a1', 'unique', 'targetAttribute' => ['a1', 'a2']] 但是它不起作用。您可以像下面这样编写您的唯一字段: [['field1','field2'], 'unique'] 现在,field1和field2都应该是唯一的 截至Yii2的官方文件: targetAttribute:应用于验证输入值唯一性的targetClass中属性的名称。如果

如何在ActiveRecord(Yii2)中设置多个字段的唯一性? 我已经按照手册上写的那样试过了

['a1', 'unique', 'targetAttribute' => ['a1', 'a2']]

但是它不起作用。

您可以像下面这样编写您的唯一字段:

[['field1','field2'], 'unique']
现在,
field1
field2
都应该是唯一的

截至Yii2的官方文件:


targetAttribute
:应用于验证输入值唯一性的
targetClass
中属性的名称。如果未设置,它将使用当前正在验证的属性的名称您可以使用数组同时验证多列的唯一性

从文档:

// 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']]

自最新的yii2文件(2017年)起,将使用目标属性

在这种情况下,字段“a1”将收到错误消息

另一种情况是:

[['a1', 'a2'], 'unique', 'targetAttribute' => ['a1', 'a2']]
现在,如果“a1”和“a2”在一起不是唯一的,“a1”和“a2”属性将收到错误消息

对于自定义消息,将使用
comboNotUnique
代替
message

[['a1', 'a2'], 'comboNotUnique' => 'Package Id already exist.', 'unique', 'attribute' => ['a1', 'a2']]

您希望每个属性单独或成对唯一?两个属性是否都在同一个模型中?targetAttribute适用于我。。属性生成错误。我觉得这里有点不对劲。文档显示,
$attributes
要由该验证器验证的属性。和
$targetAttribute
应用于验证当前属性值唯一性的ActiveRecord属性的名称。因此,
$targetAttribute
应该可以很好地工作(事实上,它对我来说很好)。即使是自己的Yi2文档示例也使用了
targetAttribute
。很好的澄清,尽管
comboNotUnique
在2.0.10中被弃用,并将在2.1中完全删除<代码>消息应继续使用。()您的解决方案不适用于相同的用例,因为它分别验证字段的唯一性。
[['a1', 'a2'], 'comboNotUnique' => 'Package Id already exist.', 'unique', 'attribute' => ['a1', 'a2']]