UniqueEntity多个字段

UniqueEntity多个字段

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

问题描述

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

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

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

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

/**
 * @ORM\Table(name="mytable")
 * @ORM\Entity
 * @DoctrineAssert\UniqueEntity(fields = {"fieldA", "fieldB"})
 */
class myClass
{
  /**
   * @ORM\Column(name="fieldA", type="string", length=128, unique=true)
   */
  protected $fieldA;

  /**
   * @ORM\Column(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文档说:

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

I think it confirms my expectations.

我在.此方法使用查询中参数之间的与"关系,从而导致问题.

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?

推荐答案

关于:

/**
 * @ORM\Table(name="mytable")
 * @ORM\Entity
 * @DoctrineAssert\UniqueEntity(fields = "fieldA")
 * @DoctrineAssert\UniqueEntity(fields = "fieldB")
 */
class myClass

?

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