In my Tag entity i need to avoid creating a tag with the same name along all tags created by a given user. There is a many-to-one relation with User entity, named user.
I’m enforcing this constraint either in database (using uniqueConstraints) and in form validation with UniqueEntity. But i can’t understand this sentence in Symfony2 documentation about this constraint:
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.
But i need that name and user are unique as a whole. Is this possible and how? Here is an example of not working one: both name and user are checked for uniqueness as singular fields.
/**
* @ORM\Entity(repositoryClass="Acme\HelloBundle\Repository\TagRepository")
* @ORM\Table(
* name="tag",
* uniqueConstraints={
* @ORM\UniqueConstraint(columns={"name", "user_id"}),
* })
* @UniqueEntity(fields={"name", "user"})
*/
class Tag implements TenantableEntityInterface
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\Column(type="string", length=31)
* @Assert\NotBlank
* @Assert\MaxLength(limit="31")
*/
private $name;
/**
* @ORM\ManyToOne(targetEntity="User", inversedBy="tags")
* @ORM\JoinColumn(nullable=false)
*/
private $user;
}
EDIT: with the definition above the form validates but i get the:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry
‘name-1’ for key ‘UNIQ_389B7835E237E06A76ED395’.
Creating two tags with the same name and the same user.
If you want the combination of both
nameanduserbe unique, then use:If you want them be unique separately, use this:
The same applies for unique constraints on the table.