Symfony2 UniqueEntity 多个字段:误报验证? [英] Symfony2 UniqueEntity multiple fields: false positive validation?

查看:15
本文介绍了Symfony2 UniqueEntity 多个字段:误报验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过对多个字段使用 UniqueEntity 验证约束来验证从表单提交的实体的唯一性.

I'm trying to validate uniqueness of an entity submitted from a form by using UniqueEntity Validation Constraint on multiple fields.

应该唯一的实体代码有两个字段 - fieldAfieldB,两者都是唯一的:

Code of the entity that should be unique has two fields - fieldA and fieldB, both unique:

/**
 * @ORMTable(name="mytable")
 * @ORMEntity
 * @DoctrineAssertUniqueEntity(fields = {"fieldA", "fieldB"})
 */
class myClass
{
  /**
   * @ORMColumn(name="fieldA", type="string", length=128, unique=true)
   */
  protected $fieldA;

  /**
   * @ORMColumn(name="fieldB", type="string", length=128, unique=true)
   */
  protected $fieldB;
}

假设我已经在数据库中有一个包含值的记录:

Suppose I already have a record in the database with values:

  • fieldA = 'value_a', fieldB = 'value_b'

现在,当我尝试使用表单中的值 (fieldA = 'value_a', fieldB = 'value_c') 提交另一个时,Symfony2 生成一个查询来检查唯一性:

Now when I try to submit another one with values (fieldA = 'value_a', fieldB = 'value_c') from a form, Symfony2 generates a query to check uniqueness:

SELECT ... FROM ... WHERE fieldA = ? AND fieldB = ? ('value_a', 'value_c')

并且验证通过,因为结果是一个空集,但是我希望它失败,因为在这种情况下 fieldA 不会是唯一的.(SQL 插入失败,'value_a' 上出现重复条目​​错误.)

And the validation passes, because the result is an empty set, but I would expect it to fail, because fieldA won't be unique in this case. (The SQL insert fails with an duplicate entry error on 'value_a'.)

Symfony2 的 UniqueEntity 文档说:

此必填选项是该实体应在其上唯一的字段(或字段列表).例如,您可以指定上面 User 示例中的 email 和 name 字段都应该是唯一的.

This required option is the field (or list of fields) on which this entity should be unique. For example, you could specify that both the email and name fields in the User example above should be unique.

我认为这证实了我的期望.

I think it confirms my expectations.

我发现了在UniqueEntityValidator 的来源(第 94 行),验证器将字段作为数组,并使用findBy"魔术查找器方法来检查唯一性.这种方法在查询中使用了参数之间的AND"关系,从而导致了问题.

I found out in the source of UniqueEntityValidator (line 94), that the validator takes the fields as an array, and uses the "findBy" magic finder method to check uniqueness. This method uses 'AND' relation between parameters in the query, which causes the problem.

是否可以以某种方式对我的问题使用此验证约束,或者我必须以另一种方式对其进行验证?

Is it possible to use this validation constraint for my problem somehow, or I have to validate it another way?

推荐答案

What about :

What about :

/**
 * @ORMTable(name="mytable")
 * @ORMEntity
 * @DoctrineAssertUniqueEntity(fields = "fieldA")
 * @DoctrineAssertUniqueEntity(fields = "fieldB")
 */
class myClass

?

这篇关于Symfony2 UniqueEntity 多个字段:误报验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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