Alex Rivera | Logout

Unique Constraints in Doctrine 2, Symfony 2

Asked 2011-12-17T14:59:28.540
36

I want to make a unique constraint in my Doctrine 2 entity such that name & test are unique column wise. Meaning

  • obj1

    • name: name1
    • test: test
  • obj2

    • name: name2
    • test: test <---- duplicated

This should trigger an error as test is duplicated.

I tried using the unique constraint (Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity). Tried

 * @UniqueEntity("name")
 * @UniqueEntity("test")

and

 * @UniqueEntity({"name", "test"})

Both seem to only trigger error when I have BOTH name and test duplicated. eg.

  • obj1

    • name: name1
    • test: test
  • obj2

    • name: name2
    • test: test

Whats the right setup? Or I might have made a mistake somewhere?

Perhaps I should include the doctrine annotation like:

@Table(name="ecommerce_products",uniqueConstraints={@UniqueConstraint(name="search_idx", columns={"name", "email"})})

But that still wont handle my symfony form validation I think?

UPDATE

My test code:

/**
 * @ORM\Entity
 * @ORM\Table(name="roles") 
 * @UniqueEntity("name")
 * @UniqueEntity("test")
 */
class Role {

    /**
     * @var integer
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue
     */
    protected $id;

    /**
     * @var string
     * 
     * @ORM\Column(type="string", length=32, unique=true)
     * @Assert\MaxLength(32)
     * @Assert\Regex("/^[a-zA-Z0-9_]+$/")
     */
    protected $name;

}

$v = $this->get('validator');

$role = new Role();
$role->setName('jm');
$role->setTest('test');
$e = $v->validate($role);
echo '=== 1 ===';
var_dump($e);
if (count($e) == 0)
    $em->persist($role);      
Edit
Report

1 Answer

57

In the Table annotation, you can also set an index for multiple columns.

/**
 * @ORM\Entity
 * @ORM\Table(name="ecommerce_products",uniqueConstraints={
 *     @ORM\UniqueConstraint(name="search_idx", columns={"name", "email"})})
 */

or with YAML format:

Namespace\Entity\EntityName:
    type: entity
    table: ecommerce_products
    uniqueConstraints:
        uniqueConstraint:
            columns: [name, email]
answered 2012-09-28T15:44:40.457

Your Answer