首页 > 解决方案 > 我如何在 CakePHP 3.9(使用 Postgres)的查询构建器中按 xxxx DESC NULLS FIRST(或 LAST)进行排序

问题描述

我写..

$query->order([
    'updated_at' => 'DESC NULL LAST',
]);

然后...

2021-04-07 16:34:58 Notice: Deprecated (16384): Passing extra sort expressions by associative array is deprecated. Use QueryExpression or numeric array instead. - /var/www/shokunin3/vendor/cakephp/cakephp/src/Database/Expression/QueryExpression.php, line: 173
 You can disable deprecation warnings by setting `Error.errorLevel` to `E_ALL & ~E_USER_DEPRECATED` in your config/app.php. in [/var/www/shokunin3/vendor/cakephp/cakephp/src/Core/functions.php, line 311]
Request URL: /hogehoge
Client IP: 192.168.1.1
Trace:
Cake\Error\BaseErrorHandler::handleError() - CORE/src/Error/BaseErrorHandler.php, line 168
deprecationWarning - CORE/src/Core/functions.php, line 311
Cake\Database\Expression\OrderByExpression::_addConditions() - CORE/src/Database/Expression/OrderByExpression.php, line 72
Cake\Database\Expression\QueryExpression::add() - CORE/src/Database/Expression/QueryExpression.php, line 173
Cake\Database\Query::_conjugate() - CORE/src/Database/Query.php, line 2260
Cake\Database\Query::order() - CORE/src/Database/Query.php, line 1191
App\Controller\FooController::bar() - APP/Controller/FooController.php, line 999
...

我应该怎么写?

最新的 CakePHP 推荐什么方法?

我很抱歉我的英语不好...

标签: phppostgresqlcakephpquery-builder

解决方案


正如错误消息所暗示的,您可以传递一个表达式来表示您可以编写任意 SQL 的方向:

$query->order([
    'updated_at' => $query->newExpr('DESC NULLS LAST'),
]);
$query->order(function (\Cake\Database\Expression\QueryExpression $exp) {
    return [
        'updated_at' => $exp->add('DESC NULLS LAST'),
    ];
});

或者您可以传递非关联数组条目,即单个字符串或表达式(但不支持自动标识符引用):

$query->order([
    'updated_at DESC NULLS LAST',
]);
$query->order(function (\Cake\Database\Expression\QueryExpression $exp) {
    return [
        $exp->add('updated_at DESC NULLS LAST'),
    ];
});

在任何情况下,请确保不要在非关联值或表达式中插入用户数据,因为它们是按原样插入到查询中的,即它们很容易被 SQL 注入!

也可以看看


推荐阅读