【发布时间】:2014-12-20 08:42:00
【问题描述】:
我试图了解多对多关系如何与 Doctrine 和 Symfony2 一起工作。
我重新创建了官方文档 (goo.gl/GYcVE0) 中显示的示例,并且我有两个实体类:User 和 Group,如下所示.
<?php
/** @Entity **/
class User
{
// ...
/**
* @ManyToMany(targetEntity="Group", inversedBy="users")
* @JoinTable(name="users_groups")
**/
private $groups;
public function __construct() {
$this->groups = new \Doctrine\Common\Collections\ArrayCollection();
}
// ...
}
/** @Entity **/
class Group
{
// ...
/**
* @ManyToMany(targetEntity="User", mappedBy="groups")
**/
private $users;
public function __construct() {
$this->users = new \Doctrine\Common\Collections\ArrayCollection();
}
// ...
}
如果我更新我的数据库,我会得到这个 MySQL 架构:
CREATE TABLE User (
id INT AUTO_INCREMENT NOT NULL,
PRIMARY KEY(id)
) ENGINE = InnoDB;
CREATE TABLE users_groups (
user_id INT NOT NULL,
group_id INT NOT NULL,
PRIMARY KEY(user_id, group_id)
) ENGINE = InnoDB;
CREATE TABLE Group (
id INT AUTO_INCREMENT NOT NULL,
PRIMARY KEY(id)
) ENGINE = InnoDB;
ALTER TABLE users_groups ADD FOREIGN KEY (user_id) REFERENCES User(id);
ALTER TABLE users_groups ADD FOREIGN KEY (group_id) REFERENCES Group(id);
问题在于,在 Symfony2 中,我需要 Entity 来生成查询,在这种情况下,我没有与表 users_group 关联的实体,因为该表是由框架。
那么,我怎样才能检索到这个关系表的相关信息呢?例如,我需要获取组中的所有用户,这些用户的 id 出现在表 users_group 中。
如何使用 DQL、QueryBuilder 或其他方法来做到这一点?
非常感谢。
【问题讨论】:
-
你的标准是什么你可以为你的标准编写mysql查询吗?所以我们会尝试在 DQL 查询中翻译它
-
@M Khalid Junaid 例如,我需要获取组中的所有用户。使用原始 SQL 应该类似于 SELECT u.id, u.name FROM Users u, Group g, users_group ug WHERE ug.group_id=5 AND u.id=ud.user_id。如您所见,我需要与表 users_group 相关的实体。
标签: php mysql symfony doctrine-orm many-to-many