[英]Select count() in Doctrine DQL with left join manyToMany unidirectional relation where user does NOT have relation specific group
[英]Equivalent SQL query in DQL with ManyToMany relation with join table
作為標題,我正在努力獲取SQL查詢的正確DQL版本(或相應的查詢生成器)。
有涉及的表: SQL圖形模式
對於ID排序的每個產品,我都需要檢索“ ord”排序的圖像。
這是SQL中的正確查詢(希望..順便說一句:P)。
SELECT
PG.product_id,
PIJG.img_id,
PI.uri,
PI.ord
FROM
ProductGeneral PG
JOIN
ProductImgJoinGeneral PIJG ON PG.product_id = PIJG.product_id
JOIN
ProductImg PI ON PIJG.img_id = PI.img_id
ORDER BY
PG.product_id ASC,
PI.ord ASC;
這些是實體(僅關系):
class ProductGeneral {
//all the standard columns are omitted
/**
* @var \Doctrine\Common\Collections\Collection
* @ORM\ManyToMany(targetEntity="AppBundle\Entity\ProductImg", inversedBy="product")
* @ORM\JoinTable(name="productImgJoinGeneral",
* joinColumns={
* @ORM\JoinColumn(name="product_id", referencedColumnName="product_id")
* },
* inverseJoinColumns={
* @ORM\JoinColumn(name="img_id", referencedColumnName="img_id")
* }
* )
*/
private $img;
}
class ProductImg {
//all the standard columns are omitted
/**
* @var \Doctrine\Common\Collections\Collection
* @ORM\ManyToMany(targetEntity="AppBundle\Entity\ProductGeneral", mappedBy="img")
*/
private $product;
}
有什么幫助嗎?
PIJG表在您的Doctrine映射中沒有映射的實體,因此您無法對其進行選擇。 但是PIJG.img_id = PI.img_id
,因此您可以執行以下操作:
$qb = $this->productGeneralRepository->createQueryBuilder('PG')
->select('PG.product_id, PI.img_id, PI.uri, PI.ord')
->innerJoin('PG.img', 'PI')
->addOrderBy('PG.product_id', 'ASC')
->addOrderBy('PI.ord', 'ASC');
然后,如果要原始DQL,只需獲取$qb->getDql()
。 多虧了您的Doctrine映射, innerJoin方法自動執行了雙重聯接
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.