Symfony2 使用查询生成器加载特定的 ManyToMany 对象

Symfony2 using Query builder to load a specific ManyToMany object

我的产品可以有很多类别。然而,在对象的一部分中,我需要获得一个特定的类别。因此,我不需要获取所有类别然后在 for 循环中搜索特定类别,我只需要获取该特定类别。为此,我正在使用查询生成器。

public function findProduct($id) {
    $qb = $this->createQueryBuilder('p')
        ->addSelect(array('p', 'cat'))  // many to many table
        ->addSelect(array('p', 'category')) // the category entity
        ->leftJoin('p.category', 'cat')
        ->leftJoin('cat.category', 'category')
        ->andWhere("category.id = 15") // error here
        ->SetParameter('id', $id);


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

通过此查询,我可以轻松地执行 $product->getCategory[0]([] since array) 并仅获取我需要的类别(在此示例中类别为 id=15)​​

问题:

但是,如果产品没有具有特定 ID 的类别.. returns 整个产品无效..

所以如果我这样做:

 $product = $em->getRepository('MpShopBundle:Product')->findProduct($id); = null

但它应该是这样的:

 $product = $em->getRepository('MpShopBundle:Product')->findProduct($id); = object

$product->getCategory() = null

如何在查询生成器中进行这项工作?这可能吗?

这应该有效。与其限制整个查询(这就是它的作用),不如限制连接。

leftJoin('cat.category', 'category', 'WITH', 'category.id = 15')

通过这种方式,只有在 id == 15 时,您才能始终获得您的产品和类别。