带连接表的Doctrine查询

时间:2017-04-01 23:03:34

标签: symfony doctrine-orm doctrine-query

我正在尝试在学说QueryBuilder

中创建此SQL查询
SELECT count(DISTINCT d.id)
FROM `discount` d
JOIN `order_discount_relationships` od ON od.discount_id = d.id
JOIN `orders` o ON o.id = od.order_id
WHERE o.status = 3  

我的两个实体是:

/**
 * @ORM\Table
 */
class Discount
{
    // ...
}

/**
 * @ORM\Table
 */
class Order
{
    // ...

    /**
     * @var Discount[]|ArrayCollection
     * @ORM\ManyToMany(targetEntity="AppBundle\Entity\Discount")
     * @ORM\OrderBy({"id" = "ASC"})
     * @ORM\JoinTable(name="order_discount_relationships",
     *      joinColumns={@ORM\JoinColumn(name="order_id", referencedColumnName="id")},
     *      inverseJoinColumns={@ORM\JoinColumn(name="discount_id", referencedColumnName="id")}
     * )
     */
    private $discounts;

    // ...
}

我想计算已使用的折扣(按状态3的顺序)

$qb = $this->createQueryBuilder('d');
$qb->select('count(DISTINCT d)')
    ->join('AppBundle:Order', 'o', 'WITH', 'o.discountCodes = d')
    ->where('o.status = :status')
    ->setParameter('status', Order::STATUS_SUCCESS)
;

但我收到了这个错误:

  

错误:无效的PathExpression。 StateFieldPathExpression或SingleValuedAssociationField预期

你知道那是怎么回事吗? 谢谢你的帮助

1 个答案:

答案 0 :(得分:1)

尝试使用member of

$qb->select('count(DISTINCT d)')
    ->join('AppBundle:Order', 'o', 'WITH', 'd member of o.discounts')
    ->where('o.status = :status')
    ->setParameter('status', Order::STATUS_SUCCESS)
;