Doctrine - Query builder - 选择leftjoin的几列

时间:2018-03-28 14:15:58

标签: symfony select doctrine left-join

我有两个实体:

  • 注意:id,title,description,isPublic,user
  • USER:id,email,firstname,lastname,password,salt,roles,tag

我想在获取数据库的所有注释时选择用户的几列(例如,为了不获取用户的密码)

所以在NoteRepository中我做了一个像这样的学说请求:

$qb = $this->createQueryBuilder('n');
//Get the owner of the knowledge
$qb
    ->leftJoin('n.user', 'owner')
    ->addSelect('owner.tag as ownerTag, owner.firstname as ownerFirstname, owner.lastname as ownerLastname')
;

return $qb->getQuery()->getResult(Query::HYDRATE_ARRAY);

(我坚持用连接子句来做,因为我们可以想象不止一个用户喜欢该笔记的所有者)

我得到以下JSON响应:

[
   {
      "0":{
         "id":6,
         "title":"A1",
         "description":"A1",
         "isPublic":false,
         "ownerTag":"#02a4c022d8",
         "ownerFirstname":"ama",
         "ownerLastname":"ama"
      }
   },
   {
      "1":{
         "id":7,
         "title":"Z1",
         "description":"Z1",
         "isPublic":false,
         "ownerTag":"#00a7bd24g8",
         "ownerFirstname":"z",
         "ownerLastname":"z"
      }
   }
]

但我希望以下回复:

[
   {
      "0":{
         "id":6,
         "title":"A1",
         "description":"A1",
         "isPublic":false,
         "owner":{
            "tag":"#02a4c022d8",
            "firstname":"ama",
            "lastname":"ama"
         }
      }
   },
   {
      "1":{
         "id":7,
         "title":"Z1",
         "description":"Z1",
         "isPublic":false,
         "owner":{
            "tag":"#00a7bd24g8",
            "firstname":"z",
            "lastname":"z"
         }
      }
   }
]

我不知道如何得到它。谢谢你帮助我;)

2 个答案:

答案 0 :(得分:0)

我发现了https://github.com/Atlantic18/DoctrineExtensions/issues/118

我不确定您是否可以使用queryBuilder直接执行此操作。

但你肯定可以在你的数组上使用PHP工作:)

答案 1 :(得分:0)

好吧,我找到了解决方案。 我需要像这样使用 PARTIAL 这个句子:

$qb = $this->createQueryBuilder('n');
//Get the owner of the knowledge
$qb
    ->leftJoin('n.user', 'owner')
    ->addSelect('PARTIAL owner.{id,tag,firstname,lastname}')
;

return $qb->getQuery()->getResult(Query::HYDRATE_ARRAY);