Doctrine2 实体关系
我是 Symfony2 的新手(几年前使用过 symfony 1.xa),我试图了解如何使用 Doctrine2 处理实体关系。 (顺便说一句,如果 Symfony2 书中有更多关系示例而不是简单地引用 Doctrine2 文档,那就太好了:-)
所以我有一个简单的产品实体,我想将其与多个类别相关(即单个产品可以属于多个类别) )。从表面上看,这看起来像是一对多的关系,但我认为这样的关系将通过数据库中的联接表来完成。所以我做了这样的事情:
class Product
{
....
/**
* @ORM\ManyToMany(targetEntity="Category");
**/
private $categories;
}
进行架构更新确实按预期在数据库中创建了连接表。但我想知道我将其设为多对多是否错误?我想我是在问最佳实践以及您将如何做到这一点?任何人都可以提供建议和/或提供示例吗?
Im new to Symfony2 (having used symfony 1.x a couple years ago) and Im trying to understand how to handle entity relationships with Doctrine2. (Incidently, it would be nice if the Symfony2 book had more relationship examples instead of simply referring to the Doctrine2 docs :-)
So I have a simple product entity that I want to relate to multiple categories (i.e. single product can be in multiple categories). On the surface this looks like a one-to-many kind of relationship right, but Im thinking a relationship like that would be done via a join table in the database. So Im doing something like this instead:
class Product
{
....
/**
* @ORM\ManyToMany(targetEntity="Category");
**/
private $categories;
}
Doing a schema update does indeed create the join table in the database as expected. But Im wondering if Im wrong in making this a many-to-many instead ? I guess Im asking about best practices and how you would do this ? Can anyone advise and/or provide examples ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的句子“单一产品可以属于多个类别”是正确的,但这句话也是正确的:“多个产品可以属于多个类别”。那是因为你没有使用好的句子,即:
这意味着你有很多一对多关系。
如果是
那么你就会有一个一对多和一个多对- 一种关系。
Your sentence "single product can be in multiple categories" is true but this one is true too : "multiple products can be in multiple categories". That's because you're not using the good sentences, which are:
This means you have a many-to-many relationship.
If it were
Then you'd have a one-to-many and a many-to-one relationship.
如果你想要多对多关系,你将需要一个中间表
If you want a many to many relationship you will need an intermediate table