【问题标题】:CakePHP SQL conversion - basic ORDER BYCakePHP SQL 转换 - 基本的 ORDER BY
【发布时间】:2013-06-10 07:55:43
【问题描述】:

我有一张表,我想先获取所有等于 26 的 id,然后将其余的按降序排序,如下所示:

row    id
---    --

1      26
2      26
3      26
4      27
5      25
6      24

通常会导致:

select id 
from table 
order by id=26 desc, id desc

我应该如何在 Cake 中构造一个find()?这是我的想法:

$this->Model->find('all', array(
    'conditions' => array('Model.id' => 26),
    'order' => array('Model.id' => 'DESC')
));

但是我应该如何告诉 Cake 检索其余的 id 并在检索到所有等于 26 的 id 后按降序对它们进行排序?

【问题讨论】:

  • array('Model.id' DESC) 不是有效的 PHP。您的 IDE 应该会告诉您这一点。
  • 刚刚编辑,忘记配对了。

标签: php mysql sql cakephp find


【解决方案1】:

试试这个。

$this->Model->find('all', array(
  'order' => array('Model.id = 26 DESC' , 'Model.id DESC')
));

【讨论】:

    【解决方案2】:

    假设您的id 字段是CakePHP 约定所定义的primaryKey,那么您的查询将只返回一个结果。因此,这里的排序无关紧要。

    我还建议您使用find('first') 来防止您获得以数字方式索引的单个结果。

    $this->Model->find('first', array('conditions' => array('id' => $id)));

    如果您想返回这一条记录,然后是所有其他记录,我会用 find('all') 来反转它。

    $this->Model->find('all', array('conditions' => array('id !=' => $id)));

    【讨论】:

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