2012-10-24 31 views
1

我想給一個變量放到查詢的字段名,所以我有一個模式:Doctrine2 QueryBuilder的 - 在字段名變量

id amazon - tesco - asda - happyshopper - 

    1 £5 - NULL - NULL -  £4.99 
    2 NULL - £2.99 - NULL -  NULL 

然後

$store = 'amazon'; 

$qb = $em->createQueryBuilder(); 
     $products = $qb->select('p')->from('MyBundle:Product', 'p') 
     ->where('p.:store IS NOT NULL') 
     ->setParameter('store', $store) 
     ->add('orderBy', 'p.onSale DESC') 
     ->setMaxResults(40) 
     ->getQuery() 
     ->getResult(); 

將返回行1.

我所做的:

->where('p.:store IS NOT NULL') 
->setParameter('store', $store) 

錯誤,錯誤。

->where(':store IS NOT NULL') 
->setParameter('store', $store) 

沒有錯誤,但不適用存儲過濾器。

回答

5

這裏簡短的回答是剛工作的店名爲手動字符串:

->where("p.$store IS NOT NULL") 

->where('p.' . $store . ' IS NOT NULL') 

長的答覆是,你的數據庫架構可以使用一些工作。例如,如果/當你想添加一個新的商店,會發生什麼?你打算添加一個新的列並重新編碼整個事情嗎?更好的解決方案是將「存儲」的概念分開,放在自己的表格中,並將所有內容一起放入不同的表格中。事情是這樣的:

Product: 
id | name | onSale 
1 | foo | 1 
2 | bar | 0 

Store: 
id | name  
1 | amazon 
2 | tesco 
3 | asda 
4 | happyshopper 

Price: 
id | productId | storeId | price 
1 | 1   | 1  | 5 
2 | 1   | 4  | 4.99 
3 | 2   | 2  | 2.99 

一旦配置表和您的映射正確,您的查詢變成了到:

$qb = $em->createQueryBuilder(); 
$products = $qb 
    ->select('product') 
    ->from('MyBundle:Price', 'price') 
    ->innerJoin('price.product', 'product') 
    ->innerJoin('price.store', 'store') 
    ->where('store.name = :store') 
    ->setParameter('store', $store) 
    ->add('orderBy', 'product.onSale DESC') 
    ->setMaxResults(40) 
    ->getQuery() 
    ->getResult(); 
+0

這就是我的下一份工作,整理出結構!謝謝。 – BobFlemming

相關問題