Yii 验证规则 - 唯一 [英] Yii validation rule - unique

查看:34
本文介绍了Yii 验证规则 - 唯一的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Yii 框架中,我可以使用唯一验证规则来检查某个条件下某个字段的唯一性(我知道有条件,但这个条件有点棘手)?即,我想通过 property_id 检查 num_days 的唯一性.

in Yii framework, can I use unique validation rule to check uniqueness of an field within some condition (I know there is criteria, but this condition is a bit tricky)? Ie, i want to check num_days unique by property_id.

表格:

NUM PROP_ID

3   4

3   5

如果我尝试插入 3、6,验证应该通过,但在 3、4 的情况下失败

validation should pass in case i try insert 3, 6, but fail in case of 3, 4

推荐答案

查看 UniqueAttributesValidator,还有 这个答案.在链接中,您将看到他们已将 $this->attributename 用于 CUniqueValidator 的 criteria 选项的 params 数组,但是出于某种原因,$this->attributename 对我来说是 null.我相信这是因为 $this 没有正确传递给验证器,所以无论如何最好使用 UniqueAttributesValidator 类,因为它只是为这些情况而设计的.

Check out UniqueAttributesValidator, and also this answer. In the links you'll see that they have used $this->attributename for the params array of the criteria option of CUniqueValidator, but for some reason $this->attributename was null for me. I believe that this is because the $this is not being passed correctly to the validator, so anyway it would be best to use the UniqueAttributesValidator class, because it has been made just for these kinds of situations.

生成的 sql 将有一个 WHERE 子句,如下所示:

The resulting sql will have a WHERE clause like this:

SELECT ... WHERE (`num`=:value) AND (`prop_id`=:prop_id) ...

对于 3、4 和通过 3、6 很容易失败.所以它应该适合你的情况.

which will easily fail for 3, 4 and pass for 3, 6. So it should work for your situation.

这篇关于Yii 验证规则 - 唯一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆