2012-10-24 6 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