Doctrine 2 查询生成器 abs 函数

2022-01-03 00:00:00 sql php mysql doctrine-orm

这项工作:

    $qb = $this->em->createQueryBuilder();

    $qb->select("abs(u.code) as code")
       ->from("User", "u")
       ->orderBy("code","ASC")
       ->getQuery()
       ->getArrayResult();

这行不通:

    $qb = $this->em->createQueryBuilder();

    $qb->select("u.code")
       ->from("User", "u")
       ->orderBy("abs(u.code)","ASC")
       ->getQuery()
       ->getArrayResult();

错误:

语法错误] 第 0 行,第 118 列:错误:预期字符串结束,得到 '('

本地学说函数 abs 仅适用于声明的选定部分,并且不要按部分订购.

The native doctrine function abs work only on a select part of statment and don't work on order by part.

观察:

1-) 我避免使用 NativeQuery.

1-) Im avoiding to use NativeQuery.

2-) u.code 是 mysql 上的 varchar 字段,需要是 varchar(有时是数字,有时是字符串),我需要像数字一样排序.

2-) u.code is a varchar fild on mysql and need to be varchar ( some times numeric and some times string), and i need to order then like a number in numeric case.

有什么帮助吗?

推荐答案

解决了 atmaThank 的 abs() 确实不能直接在 orderBy 中工作,而是作为别名.

Solved atma thank's abs() realy doesn't work directly in orderBy but as an alias.

解决方案

SELECT field1,field2,abs(field3) AS abs_field3 
FROM table 
ORDER BY abs_field3 ASC

Obs:这是一个原则限制,而不是 mysql 限制,mysql 支持 abs 直接按部分订购.

Obs: It's a doctrine limitation, not a mysql limitation, mysql suports abs direct on order by part.

相关文章