Doctrine2 QueryBuilder - 字段名称中的变量

Bob*_*ing 1 doctrine query-builder symfony doctrine-orm

我试图将一个变量放入查询中的字段名称,所以我有一个架构:

  id amazon - tesco - asda - happyshopper - 

  1   £5    - NULL  - NULL  -     £4.99
  2   NULL  - £2.99 - NULL  -     NULL
Run Code Online (Sandbox Code Playgroud)

然后

$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();
Run Code Online (Sandbox Code Playgroud)

将返回第1行.

我做了什么:

->where('p.:store IS NOT NULL')
->setParameter('store', $store)
Run Code Online (Sandbox Code Playgroud)

是不正确的,它是错误的.

->where(':store IS NOT NULL')
->setParameter('store', $store)
Run Code Online (Sandbox Code Playgroud)

不会出错,但不会应用商店过滤器.

Tho*_*ley 6

这里简短的回答是手动将商店名称用于字符串:

->where("p.$store IS NOT NULL")
Run Code Online (Sandbox Code Playgroud)

要么

->where('p.' . $store . ' IS NOT NULL')
Run Code Online (Sandbox Code Playgroud)

答案很长,你的数据库架构可以使用一些工作.例如,当您想要添加新商店时会发生什么?你要添加一个新列并重新编写整个代码吗?更好的解决方案是将"store"的概念分开,将其放在自己的表中,并将所有内容连接在一个不同的表中.像这样的东西:

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
Run Code Online (Sandbox Code Playgroud)

正确配置表和映射后,查询将变为:

$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();
Run Code Online (Sandbox Code Playgroud)