理论中的多对多关系 [英] many-to-many relationship in doctrine

查看:77
本文介绍了理论中的多对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的系统上有几张表:

news
--id
--title
--content

video
--id
--title
--url

album
--id
--title

现在,我需要做一个与这个表格的多对多关系,但是以灵活的方式。我创建了一个名为links的表格,具有以下结构:

Now, I need to do a many-to-many relatioship with this tables, but in a flexible way. I created a table called 'links' with the below structure:

links
--parent_entity (example: news)
--parent_id   (example: 5)
--child_entity (exmaple: video)
--child_id (example: 2)

如何使用Doctrine映射?

How can I map this using Doctrine?

推荐答案

不可能,因为你不能做正确的连接。在这种情况下,连接将取决于parent_entity和child_entity中的值(即每行可能需要加入到不同的表)。另外,学说如何知道哪一种记录类型会被水合(即因为它依赖于实体类型)。

This is not possible because you cannot do a proper join. The join in this case will depend on the value in parent_entity and child_entity (ie. each row may need to join to a different table). In addition, how will doctrine know which record type to hydrate (ie. because it is dependent on the entity type).

您可以通过在您的连接中使用WITH子句来拉这样的东西(尽管很奇怪)。例如,您可以在新闻模型的setUp()方法中执行以下操作:

You may be able to pull something like this off (albeit it will be weird) by using the WITH clause on your joins. For example, in the setUp() method of your news model you could do:

$this->hasMany('Links as NewsVideoLinks', array('local' => 'id', 'foreign' => 'parent_id'));

在您的链接模型设置中:

And in the setup of your Links model:

$this->hasMany('Videos as videos', array('local' => 'child_id', 'foreign' => 'id'));

您需要在Links模型中定义所有连接组合。我的意思是,你需要告诉它,它有很多新闻和专辑,同时使用child_id和parent_id。

You would need to define all combinations of joins in the Links model. What I mean is, you would need to tell it that it has many news and albums as well using both the child_id and parent_id.

然后在你的查询,你会需要执行以下操作:

And then in your query, you would need to do something like:

$query = Doctrine_Query::create();
$query->from('News n');
$query->innerJoin("n.NewsVideoLinks as links WITH parent_entity = 'news'");
$query->innerJoin("links.Videos as vids WITH child_entity = 'videos'");
$results = $query->execute();

正如你所看到的,这很麻烦。我强烈建议为每个关系创建连接表。您还可以通过加入每个连接表来获得您要查找的内容。

As you can see this is very cumbersome. I would highly recommend creating join tables for each relation. You would still get what you are looking for by joining out to each join table.

这篇关于理论中的多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆