Reputation: 4650
I couldn't find documentation with this written in a way I can understand it, so I'm asking you for help. This question is related to Unique entity - Symfony2
I have a table called category with three fields - id, fos_user_id and name. The other table is called fos_user and has fields id, username and so on.
I want categories to be unique for user. One user can't have two ctegories with name "Food", but all of the users can have category called "Food".
In the other question I was adviced to try something like this:
* @ORM\Table(name="categories",
* uniqueConstraints={@ORM\UniqueConstraint(name="name_user_id__idx",
* columns={"name", "user_id"})})
and I tried this:
/**
* @ORM\Entity
*
* @ORM\Table(name="category",
* uniqueConstraints={@ORM\UniqueConstraint(name="name_user_idx",
columns={"name", "fos_user_id"})}))
* @ORM\Entity(repositoryClass="Acme\BudgetTrackerBundle\Entity\CategoryRepository")
* @UniqueEntity(fields={"name", "fos_user_id"}, message="There already is such a category.")
*/
but I get this error:
The field 'fos_user_id' is not mapped by Doctrine, so it cannot be validated for uniqueness.
I can't quite understand the error. And I don't understand the part with the constraints. Is this the right syntax and the right thing to write?
Thank you very much in advance!
PS : Sorry for opening a new question, if I shouldn't, but I added a lot of new things and decided that a new qusetion is better than editing the old one and asking in the comments.
Upvotes: 1
Views: 7957
Reputation: 5158
For relations like Category, User etc... you should not use unique constraints on columns but on relations. For example:
instead of
@UniqueEntity(fields={"name", "fos_user_id"})
try
@UniqueEntity(fields={"name", "user"})
where "user" is the name of mapped field to relation with User entity.
Upvotes: 5