DQL 中的等效 SQL 查询与多对多关系与连接 table

Equivalent SQL query in DQL with ManyToMany relation with join table

如标题所示,我正在努力获取 SQL 查询的正确 DQL 版本(或相应的查询构建器)。

涉及的表有: SQL Graphic Schema

我需要为按 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 table 在你的 Doctrine 映射中没有映射的实体,所以你不能 SELECT 它。但是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 方法自动执行双 JOIN