I'm triyng to understand how the many to many relationship works with Doctrine and Symfony2.
I've recreated the example shown in the official documentation (goo.gl/GYcVE0) and i have two Entity Classes: User and Group as you can see below.
<?php
/** @Entity **/
class User
{
// ...
/**
* @ManyToMany(targetEntity="Group", inversedBy="users")
* @JoinTable(name="users_groups")
**/
private $groups;
public function __construct() {
$this->groups = new DoctrineCommonCollectionsArrayCollection();
}
// ...
}
/** @Entity **/
class Group
{
// ...
/**
* @ManyToMany(targetEntity="User", mappedBy="groups")
**/
private $users;
public function __construct() {
$this->users = new DoctrineCommonCollectionsArrayCollection();
}
// ...
}
If i update my DB i get this MySQL Schema:
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);
The problem is that in Symfony2 I need the Entity to generate a query and in this case I don't have an Entity associated to the table users_group
because this table is created automatically by the framework.
So, how can I retrieve the information related to this relationship table? For example I need to get all the Users in a Group which are the users that have an id that appears in the table users_group
.
How can I do that using the DQL, QueryBuilder or other methods?
Thanks a lot.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…