【问题标题】:How to implement conditional ordering?如何实现条件排序?
【发布时间】:2017-05-03 08:38:23
【问题描述】:

我正在尝试了解如何在 ORM find() 方法中的 cakephp3 订单函数中创建自定义订单函数。

假设我有以下模型

User
  name
  ...
  custom_data

custom_data
   type

每个用户都有一个自定义数据,其中类型是 [20,30,40] 之一。

我需要按以下方式按这种类型订购

if ( type == 20 ) {
    // put in first positions
} else {
   // put this records after users with custom_data->type != 20 
}

我需要在分页器中使用它,所以我需要类似的东西

$this->Users
   ->find()
   ->where([ something ] )
   ->order( 'ASC' => here is my custom function )

有什么建议吗?

【问题讨论】:

    标签: cakephp orm query-builder cakephp-3.x


    【解决方案1】:

    首先,从您的描述来看,您似乎需要使用DESC,因为您说您首先需要符合条件的记录。这些记录将按升序排列在最后。

    话虽如此,最简单的方法是使用基本条件,即 SQL 明智的类似:

    ORDER BY type = 20 DESC
    

    也可以使用CASE 语句来解决,但如果你有这么简单的要求,这并不是必需的。

    $query = $this->Users->find();
    $query
        ->where(/* .. */)
        ->orderDesc(
            $query->newExpr()->add(['type' => 20])
        );
    

    可以通过对order()、orderAsc()、orderDesc() 的额外调用来添加更多订购语句。

    另见

    【讨论】:

      猜你喜欢
      • 2021-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多