symfony - Doctrine2 QueryBuilder - 字段名称中的变量

标签 symfony doctrine-orm doctrine query-builder

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

  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)

没有错误,但没有应用商店过滤器。

最佳答案

这里的简短回答是将商店名称手动输入到字符串中:

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

关于symfony - Doctrine2 QueryBuilder - 字段名称中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13053616/

相关文章:

php - symfony 错误 : Expected =, <, <=, <>, >, >=, !=, 得到 '.'

url - Symfony2 url层次结构

php - Symfony2 Ajax 无限滚动

mysql - 带日期和限制的查询(DQL 中可选)

symfony - Doctrine2 "order by"在 "group by"之前

php - Symfony2 OneToMany双向引用非id列

Symfony2 : Code structure for website, 移动网站和API?

forms - symfony2 嵌入式集合编辑表单

php - Doctrine DBAL 可以批量插入吗?

mongodb - 具有 Doctrine mongodb odm 的唯一索引