这是我在Symfony2项目中的查询,使用原则:
$qb->select(array('r', 'fp', 'p'))
->from('Farmerguide'BackendBundle'Entity'Farmerproduct', 'fp')
->innerJoin('fp.product', 'p')
->innerJoin('p.rubric', 'r')
->andWhere('fp.farmer= :id')
->setParameter('id', $farmerId);
有关表/实体的信息:Farmerproduct有一个id、farmer_id和一个product_idproduct有一个id和rubric_id(product是rubric的某种"子目录")
我现在想要所有的准则,没有其他任何东西,为一个农民。但是当我更改select
-部分时,我遇到了一个错误,它说它需要选择所有的joined
实体。。。
好吧,现在我得到了所有的加入信息,所以对于一个农民的100种产品,我得到了每个带有红色和农民的产品(我不知道为什么我也得到了农民…)
有什么建议吗?
您必须选择DQL查询的根实体。假设您没有双向关联,它看起来如下:
SELECT
r
FROM
Farmerguide'BackendBunle'Entity'Rubric r
WHERE
r.id IN (
SELECT
r2.id
FROM
Farmerguide'BackendBundle'Entity'Farmerproduct fp
JOIN
fp.product p
JOIN
p.rubric r2
WHERE
fp.farmer = :id
)
在QueryBuilder
API中,如下所示:
$qb1 = $em->createQueryBuilder();
$qb2 = $em->createQueryBuilder();
$qb2
->select(array('r2.id'))
->from('Farmerguide'BackendBundle'Entity'Farmerproduct', 'fp')
->innerJoin('fp.product', 'p')
->innerJoin('p.rubric', 'r2')
->andWhere('fp.farmer= :id')
$qb1
->select('r')
->from('Farmerguide'BackendBunle'Entity'Rubric', 'r')
->where($qb->expr()->in('r.id', $qb2->getDQL()))
$rubrics = $qb1
->setParameter('id', $farmerId)
->getQuery()
->getResult();
如果您在这里并不真正需要QueryBuilder
,可以考虑使用普通DQL:因为您看到它更简单。