Query Builder将具有oneToMany映射的对象作为数组返回

时间:2014-08-05 14:27:24

标签: php doctrine-orm zend-framework2 query-builder

我需要更新我的代码以包含Media,它是在Object.php实体中单向映射的oneToMany。理想情况下,即使没有媒体,我也需要我的代码返回所有对象,目前它只返回带有媒体的对象,但如果有多个媒体项则会返回多个结果。

如果您认为我重构代码并使用更简单的东西,而不是让我知道 - 我没有找到使用getRepo()和findBy()函数获取feed的方法(没有序列化?)

这是我的代码:

// Build object QB
$emObject         = $this->objectService->getManager();
$qbObject         = $emObject->createQueryBuilder();
$qbObject->addSelect(['o.id', 'o.title', 'o.description', 'm as multimedia', 'c.id as category_id', 'c.name as category_name'])
        ->from('Application\Entity\Cms\Object', 'o')
        ->leftJoin('Application\Entity\Cms\Media', 'm', 'WITH', '1 = 1')
        ->leftJoin('o.media', 'om')
        ->leftJoin('Application\Entity\Cms\Category', 'c', 'WITH', '1 = 1')
        ->leftJoin('o.category', 'oc')
        ->andWhere('om.id = m.id')
        ->andWhere('oc.id = c.id')
        ->andWhere('o.member = :member')
        ->setParameter('member', $member);

$objectList = $qbObject->getQuery()->getResult(Query::HYDRATE_ARRAY);

$viewModel->setVariables(['object' => $objectList]);

return $viewModel;

返回:

{
  "object": [
    {
      "multimedia": {
        "id": 22,
        "title": null,
        "url": "\/srv\/pois\/cms\/e9049aaac93ce96c81e16340027a804b.png"
      },
      "id": 34,
      "title": "imgTest",
      "description": "f",
      "category_id": 1,
      "category_name": "Chambres"
    },
    {
      "multimedia": {
        "id": 23,
        "title": null,
        "url": "\/srv\/pois\/cms\/ce0c7d669c567369485a01c65197943f.png"
      },
      "id": 34,
      "title": "imgTest",
      "description": "f",
      "category_id": 1,
      "category_name": "Chambres"
    }
  ]
}

但是,我需要将多媒体对象放在一个数组中,只返回1个对象,如:

{
  "object": [
    {
      "multimedia": {
          1: {
            "id": 22,
            "title": null,
            "url": "\/srv\/pois\/cms\/e9049aaac93ce96c81e16340027a804b.png"
          },
          0: {
            "id": 23,
            "title": null,
            "url": "\/srv\/pois\/cms\/ce0c7d669c567369485a01c65197943f.png"
          },
      }
      "id": 34,
      "title": "imgTest",
      "description": "f",
      "category_id": 1,
      "category_name": "Chambres"
    }
  ]
}

1 个答案:

答案 0 :(得分:1)

我总是使用没有QueryBuilder的DQL查询。我想这就是你想要的:

$query = $this->entityManager->createQuery(
    "SELECT o, m FROM 'Application\Entity\Cms\Object' o JOIN o.multimedia m WHERE o.member = :member"
);
$query->setParameters(array('member' => $member));
$objects = $query->getResult();

我认为这不比那复杂。

在QueryBuilder中,它可能如下所示:

$qb = $this->entityManager->createQueryBuilder();
$qb->select('o', 'm')
   ->from('Application\Entity\Cms\Object', 'o')
   ->leftJoin('o.multimedia', 'm')
   ->where('o.member = :member')
   ->setParameter('member', $member);

return $qb->getQuery()->getResult();

如果没有返回您想要的内容,请返回详细信息。我也许可以帮忙得到你想要的东西。