我试图理解 Doctrine 和 Symfony2 中的多对多关系是如何运作的。
我重新创建了官方文档(goo.gl/GYcVE0)中显示的示例,并且我有两个实体类:User and 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 或其他方法来做到这一点?
多谢。