简体   繁体   English

Symfony2 - 查询生成器LIKE空值

[英]Symfony2 - Query Builder LIKE null values

I'm trying to build a dynamic query in response to a custom search from users. 我正在尝试构建动态查询以响应用户的自定义搜索。 I have an issue: when I'm building the query, I don't have the results because the SELECT LIKE column comparison doesn't work with NULL values. 我有一个问题:当我构建查询时,我没有结果,因为SELECT LIKE列比较不适用于NULL值。 How can I work around this issue, considering that query is dynamically built? 考虑到动态构建查询,我该如何解决这个问题? So, users can give values or not to search criteria... 因此,用户可以给出值或不给搜索条件......

This is my code: 这是我的代码:

$qb->add('select', 'f')
   ->add('from', 'Bundle:Object f')
   ->add('where', $qb->expr()->andx(
            $qb->expr()->like('f.c1',':c1'),
            $qb->expr()->like('f.c2',':c2'),
            $qb->expr()->like('f.c3',':c3')))
   ->add('orderBy', 'f.nnumCatalogo ASC');
if ($data->getField1() != null) {
  $isField1 = true;
}
if ($data->getField2() != null) {
  $isField2 = true;
}
if ($data->getField3() != null) {
  $isField3 = true;
}
if ($isField1) {
  $qb->setParameter('c1', $data->getField1());
} else {
  $qb->setParameter('c1', '%');
}
if ($isField2) {
  $qb->setParameter('c2', $data->getField2());
} else {
  $qb->setParameter('c2', '%');
}
if ($isField3) {
  $qb->setParameter('c3', $data->getField3());
} else {
  $qb->setParameter('c3', '%');
}

With this code I have no results becuase of NULL values in some columns not selected with LIKE '%' (mysql). 使用此代码,我没有结果,因为某些列中没有使用LIKE'%'(mysql)选择的NULL值。

Try this: 尝试这个:

$qb->add('select', 'f')->add('from', 'Bundle:Object f');
if ($data->getField1() != null) {
    $qb->andWhere('f.c1 like :c1')
    ->setParameter('c1', $data->getField1());
}
if ($data->getField2() != null) {
    $qb->andWhere('f.c2 like :c2')
    ->setParameter('c2', $data->getField2());
}
if ($data->getField3() != null) {
    $qb->andWhere('f.c3 like :c3')
    ->setParameter('c3', $data->getField3());
}
$qb->add('orderBy', 'f.nnumCatalogo ASC');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM