Faery
Faery

Reputation: 4650

Unique entity - Symfony2

Unique entity works great for me, but there is one problem. I have users and categories. Each category has user_id in order to be claer which user has created it and to which user it belongs. What I want is the categories to be unique for each user - so one user can't have 2 categories with the same name, but two different users can have exactly the same categories.

Is there a way to achive this in a better way with something like unique entity or it's better to write a function which counts the number of categories by name and user and use it for the validation - if there is already a category with the given name for this user - print a meassage, else create the new category.

Upvotes: 0

Views: 408

Answers (1)

Vadim Ashikhman
Vadim Ashikhman

Reputation: 10136

You can just create unique index for name and user_id columns in the categories table.

Something like:

* @ORM\Table(name="categories",
*            uniqueConstraints={@ORM\UniqueConstraint(name="name_user_id__idx", 
*                                                     columns={"name", "user_id"})})

And pass these field names to the UniqueEntity

Upvotes: 4

Related Questions