简体   繁体   English

Doctor DQL Manytomany查询以预取外部实体

[英]Doctrine dql manytomany query to pre fetch foreighn entitties

I have a User entity and Role entity. 我有一个用户实体和角色实体。 A user can have many roles and a role can have many users. 一个用户可以具有多个角色,而一个角色可以具有多个用户。 The parts that matter (I think) are the following: 重要的部分(我认为)如下:

In User.php 在User.php中

/**
 * @ORM\ManyToMany(targetEntity="Role",inversedBy="users")
 * @ORM\JoinTable(name="user_role",
 *      joinColumns={@ORM\JoinColumn(name="userid", referencedColumnName="id")},
 *      inverseJoinColumns={@ORM\JoinColumn(name="roleid", referencedColumnName="id")}
 *      )
 */
protected $roles;
public function __construct(){
    $this->roles = new ArrayCollection();
}

In Role.php: 在Role.php中:

/**
 * @ORM\ManyToMany(targetEntity="User", mappedBy="roles")
 * @ORM\JoinTable(name="user_role",
 *      joinColumns={@ORM\JoinColumn(name="roleid", referencedColumnName="id")},
 *      inverseJoinColumns={@ORM\JoinColumn(name="userid", referencedColumnName="id")}
 *      )
 */
protected $users;
public function __construct(){
    $this->users = new ArrayCollection();
}

Trying the following query gives me a User that gets it's id and name field replaced with Role id and name 尝试以下查询使我得到一个User,该用户将其id和name字段替换为Role id和name

$result = $this->getEntityManager()->createQuery('SELECT 
    u.id, u.username, u.name, u.email, r.id, r.name
    FROM mytestBundle:User u
    LEFT JOIN u.roles r
    WHERE u.id = :id')
        ->setParameter('id', $id)
        ->getArrayResult();

The following gives me an error: Error: Cannot select entity through identification variables without choosing at least one root entity alias. 以下内容给我一个错误: Error: Cannot select entity through identification variables without choosing at least one root entity alias.

$result = $this->getEntityManager()->createQuery('SELECT 
    u.id, u.name, r
    //... rest is same

The following gives me the result as I expect but includes too many user fields. 以下内容提供了我期望的结果,但其中包含过多的用户字段。 One user watching the profile of another user can't see the user's email, password, salt, ... but is allowed to see the user's roles: 一个正在查看另一个用户的个人资料的用户看不到该用户的电子邮件,密码,盐...,但是被允许查看该用户的角色:

$result = $this->getEntityManager()->createQuery('SELECT 
    u, r

So the question is: How do I select only certain user fields and have doctrine nest Roles in a user record without it throwing an error? 因此,问题是:如何仅选择某些用户字段并在用户记录中包含教义嵌套角色而不会引发错误?

Posted too early, sorry. 发布得太早了,对不起。

This errors is quite common and many SO answers do not apply to my situation but this one does. 这个错误是很常见的,许多SO答案并不适用于我的情况,但是这一次呢。

Using partial solved my problem: 使用局部解决了我的问题:

$result = $this->getEntityManager()->createQuery('SELECT 
    partial u.{id, name}, r

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

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