2015-04-27 88 views
3

我真的不好受這個查詢轉換成學說:笨到Symfony2的與Doctrine2

public function get_order($id) 
{ 
    $this->db->select('*'); 
    $this->db->from('tbl_orderline'); 
    $this->db->join('tbl_order', 'tbl_order.orderNo = tbl_orderline.orderNo'); 
    $this->db->join('tbl_customer', 'tbl_customer.customerNo = tbl_order.customerNo'); 
    $this->db->join('tbl_product', 'tbl_product.productNo = tbl_orderline.productNo'); 
    $this->db->where('tbl_order.orderNo', $id); 

    $query = $this->db->get(); 
    return $query->result_array(); 
} 

能否請你幫我這個? 有什麼建議嗎?謝謝

+0

您的實體已映射?您用於加入的關係存在於映射中? – Jean

回答

2
// if you're currently in custom Repository class then: 
$qb = $this->createQueryBuilder('ol'); 

// if you're in a controller, then should be: 
$qb = $em->getRepository('AppBundle:OrderLine')->createQueryBuilder('ol'); // Or whatever your bundle name is. 

// query alias legend: 

// ol - order line 
// o - order 
// c - customer 
// p - product 

// Your query builder should look something like this: 

$qb 
    ->addSelect('o, c, p') 
    ->leftJoin('ol.order', 'o') // this is your relation with [order] 
    ->leftJoin('o.customer', 'c') // this is your relation with [customer] from [order] 
    ->leftJoin('ol.product', 'p') // this is your relation with [product] from [order line] 
    ->where($qb->expr()->eq('ol.id', ':orderLineId') 
    ->setParameter('orderLineId', $id) 
    ->getQuery() 
    ->getOneOrNullResult(); 

注:

既然你沒有提供任何實體映射,這是完全脫離了藍色的。您很可能會更改此查詢中的屬性,但至少應該爲您提供所需的開始。

不要猶豫,問問,如果你不明白的東西。

1

我總是發現它更容易直寫dql。試圖用複雜的東西使用querybuilder讓我感到非常緊張。這顯然要求您在實體中映射正確的關係,或者註釋或使用orm文件。

顯然很難測試我在下面放置什麼,所以你可能需要調試一點。

$query = $this->getEntityManager()->createQuery(
'select orderline, order, customer, product 
from BundleName:tlb_orderline orderline 
join orderline.orderNo order 
join order.customerNo customer 
join orderline.productNo product 
where order.orderNo = :id'); 

$query->setParameter('id' => $id); 

return $query->getResult(); 
+0

還有其他方法嗎?我的意思是我沒有使用我的代碼的dql,我認爲如果我將我的代碼與dql混合在一起看起來不太好。 – User122113

+0

但你的帖子標題說你使用doctrine2(哪個是dql)?你現在使用兩種方法得到2個答案。兩者都應該完成這項工作。 – DevDonkey