繁体   English   中英

使用Doctrine和Symfony2查询多对多关系

[英]Query on a many-to-many relationship using Doctrine with Symfony2

我很想知道多对多关系如何与Doctrine和Symfony2一起工作。

我重新创建了官方文档(goo.gl/GYcVE0)中显示的示例,我有两个实体类: 用户 ,如下所示。

<?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中我需要实体来生成查询,在这种情况下,我没有与表users_group关联的实体,因为该表是由框架自动创建的。

那么,我如何检索与此关系表相关的信息? 例如,我需要获取组中的所有用户,这些用户具有出现在表users_group的id。

我怎样才能使用DQL,QueryBuilder或其他方法?

非常感谢。

您可以编写一个连接DQL查询,如下所示

$em = $this->getContainer()->get('doctrine')->getManager();
$repository = $em->getRepository('YourNamespaceYourBundle:User');
$query = $repository->createQueryBuilder('u')
    ->innerJoin('u.groups', 'g')
    ->where('g.id = :group_id')
    ->setParameter('group_id', 5)
    ->getQuery()->getResult();

您在User实体中对groups属性的映射将处理连接部件本身,您不必在DQL查询中提及连接表

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM