Doctrine2添加' LIKE' addOrderBy

时间:2015-11-26 14:54:12

标签: php doctrine-orm query-builder

我尝试使用Doctrine2查询构建器创建的查询是:

SELECT * FROM tbl t0_ ORDER BY t0_.column1 LIKE '%value%' DESC, t0_.id DESC

我现在所拥有的:

    $qb = $this->_em->createQueryBuilder();
    $qb->add('select', 'p')
        ->add('from', 'S2\Entity\Tbl p')
        ->addOrderBy('p.column1 LIKE "%value%"', 'DESC')
        ->addOrderBy('p.id', 'desc');

这导致异常Error: Expected end of string, got 'LIKE'

如何将此like添加到我的addOrderBy

修改

作为替代方案,我也尝试过:

$qb = $this->_em->createQueryBuilder();
$qb->add('select', 'p')
    ->add('select', 'LOCATE("value", p.column1) as HIDDEN field_search')
    ->add('from', 'S2\Entity\Tbl p')
    ->addOrderBy('field_search', 'DESC')
    ->addOrderBy('p.id', 'desc');

但是这引发了不知道locate是什么的例外。

我想要这样做的原因是在行的其余部分上方显示value行。

例如,我的表格如下:

id | column1
1  | some text
2  | some content
3  | contains value
4  | Could contain value
5  | some more text
6  | lots of text

我追求的输出是:

id | column1
4  | Could contain value
3  | contains value
6  | lots of text
5  | some more text
2  | some content
1  | some text

所以id按降序排序,包含value的行出现在结果集的顶部。

1 个答案:

答案 0 :(得分:1)

请使用下一个查询按相关性过滤数据:

    $qb = $this->_em->createQueryBuilder();
    $result = $qb->select("p")
        ->from('S2\Entity\Tbl', 'p')
        ->addSelect("(CASE
                   WHEN p.column1 like 'Text %' THEN 0
                   WHEN p.column1 like 'Text%' THEN 1
                   WHEN p.column1 like '%Text' THEN 2
                   ELSE 3 END) AS HIDDEN ORD "
        )
        ->addOrderBy('ORD', 'ASC')
        ->getQuery()
        ->getResult();