【问题标题】:Symfony2 - Query Builder LIKE null valuesSymfony2 - 查询生成器 LIKE 空值
【发布时间】:2012-10-05 21:09:20
【问题描述】:

我正在尝试构建一个动态查询来响应用户的自定义搜索。我有一个问题:当我构建查询时,我没有结果,因为 SELECT LIKE 列比较不适用于 NULL 值。考虑到查询是动态构建的,我该如何解决这个问题?所以,用户可以给值或不给搜索条件...

这是我的代码:

$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', '%');
}

使用此代码,我没有结果,因为某些列中的 NULL 值未使用 LIKE '%' (mysql) 选择。

【问题讨论】:

    标签: symfony null doctrine query-builder


    【解决方案1】:

    试试这个:

    $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');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-23
      • 2012-03-18
      • 1970-01-01
      • 2022-11-02
      • 1970-01-01
      • 2017-09-12
      相关资源
      最近更新 更多