Doctrine QueryBuilder从一对多关系中选择

时间:2018-06-12 06:38:31

标签: symfony doctrine-orm

我有两个具有一对多关系的实体。我需要从实体1和实体2中选择名称

$qb
    ->select(['f.name1', 'c.name2'])
    ->from('BundleOne:EntityOne', 'c')
    ->innerJoin('c.EntityTwo', 'f');

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

通过上述查询,我​​得到以下结果:

1 => array:2 [ 
    "name1" => "xyz" 
    "name2" => "n1" 
] 
2 => array:2 [ 
    "name1" => "xyz" 
    "name2" => "n2" 
] 
3 => array:2 [ 
    "name1" => "abc" 
    "name2" => "n3" 
] 
4 => array:2 [ 
    "name1" => "abc" 
    "name2" => "n4" 
]

正如您所注意到的,由于这是一对多的关系,name1可能有多个name2与之关联,而不是上述,我想返回如下结果:

"xyz" => array:2 ["n1", "n2"]
"abc" => array:2 ["n3", "n4"]

这是name1作为包含所有name2

的数组的键

这可能吗?

1 个答案:

答案 0 :(得分:0)

你可以这样做(你没有提供任何真实的实体例子,所以我自己创建了两个,只是为了简单起见):

#Category 1-N Product
#AppBundle/Repository/CategoryRepository.php
public function getProducts()
{
    $qb = $this
        ->createQueryBuilder('c')
        ->select('c, p')
        ->leftJoin('c.products', 'p')
    ;

    return $qb->getQuery()->getArrayResult();
}

然后在控制器中:

#AppBundle/Controller/DefaultController.php
public function indexAction()
{
    $categories = $this->getDoctrine()->getRepository('AppBundle:Category')->getProducts();
    $results = [];
    foreach($categories as $category) {
        $results[$category['name']] = $category['products'];
    }

    return $this->render('...', [
        'results' => $results,
    ]);
}

结果将显示如下:

array:2 [▼
  "category1" => array:3 [▼
    0 => array:2 [▼
      "id" => 1
      "name" => "product1"
    ]
    1 => array:2 [▼
      "id" => 2
      "name" => "product2"
    ]
    2 => array:2 [▼
      "id" => 3
      "name" => "product3"
    ]
  ]
  "category2" => array:2 [▼
    0 => array:2 [▼
      "id" => 4
      "name" => "product1"
    ]
    1 => array:2 [▼
      "id" => 5
      "name" => "product2"
    ]
  ]
]