【问题标题】:How to select only some fields from entity with ManyToMany related table如何从具有 ManyToMany 相关表的实体中仅选择某些字段
【发布时间】:2015-12-24 13:55:38
【问题描述】:

我有两个实体:BlogPost 和 Category。 BlogPost 实体与实体类别具有多对多单向关系。我在 BlogPost 存储库中编写了一个函数,仅获取 BlogPost 实体的某些字段和 Category 实体的所有字段。就是这样:

private function getLitePosts(){
    $q = $this->_em->createQuery(
        'select p.id as pid, p.updateDate, p.postTitle, c from ESGISGabonPostBundle:CorporatePost p left join p.categories c'
    );
    return $q->getResult();
}

运行时出现错误:

"message": "[Semantical Error] line 0, col -1 near 'select p.id,': Error: Cannot select entity through identification variables without choosing at least one root entity alias."

我不知道如何处理它。我除了得到这样的东西(以 json 表示):

[
    {
        "pid": 1,
        "updateDate": 2015-09-26T00:00:00+0100,
        "postTitle": "This is a test",
        "categories": [
            {
                "id": 1,
                "title": "Uncathegorized"
            }
        ]
    },
    {
        "pid": 1,
        "updateDate": 2015-09-26T00:00:00+0100,
        "postTitle": "This is a test 2",
        "categories": [
            {
                "id": 1,
                "title": "Uncathegorized"
            }
        ]
    }
]

有人可以帮帮我吗?

【问题讨论】:

    标签: symfony doctrine-orm many-to-many


    【解决方案1】:

    我建议对这个简单的操作使用查询生成器。

    $query = $this->createQueryBuilder('p')
        ->select('p.id as pid, p.updateDate, p.postTitle, c')
        ->leftJoin('p.categories', 'c')
        ->getQuery();
    
    return $query->getResult();
    

    更多灵感can be found in this answer

    【讨论】:

      【解决方案2】:

      我终于找到了解决办法:

      $query = $this->createQueryBuilder('p')
              ->select('partial p.{id, updateDate, postTitle}')
              ->leftJoin('p.categories', 'c')
              ->addSelect('partial c.{id}')
              ->getQuery();
      
      return $query->getArrayResult();
      

      它像我想要的那样工作。感谢 Tomáš Votruba 的回答。

      【讨论】:

        猜你喜欢
        • 2011-11-13
        • 2016-12-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-27
        • 2018-04-09
        • 1970-01-01
        相关资源
        最近更新 更多