独特的实体 - Symfony2 [英] Unique entity - Symfony2
问题描述
唯一实体对我来说很好用,但有一个问题.我有用户和类别.每个类别都有 user_id 以便清楚哪个用户创建了它以及它属于哪个用户.我想要的是每个用户的类别都是唯一的 - 所以一个用户不能有 2 个同名的类别,但两个不同的用户可以有完全相同的类别.
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.
推荐答案
您可以只为类别表中的 name 和 user_id 列创建唯一索引.
You can just create unique index for name and user_id columns in the categories table.
类似于:
* @ORM\Table(name="categories",
* uniqueConstraints={@ORM\UniqueConstraint(name="name_user_id__idx",
* columns={"name", "user_id"})})
并将这些字段名称传递给 UniqueEntity
And pass these field names to the UniqueEntity
这篇关于独特的实体 - Symfony2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!