2017-04-01 97 views
0

我想在一個學說來創建此SQL查詢QueryBuilder主義查詢與連接表

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; 

    // ... 
} 

我'd要計算已經使用的折扣(狀態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) 
; 

但我得到這個錯誤:

Error: Invalid PathExpression. StateFieldPathExpression or SingleValuedAssociationField expected

你知道怎麼做嗎? 感謝您的幫助

回答

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) 
;