mysql - 如何在cakephp 3中编写orderByField查询

标签 mysql sql cakephp-3.0

在sql中,我有这个查询,它工作正常,并按“order BY Field”中的给定数组进行排序。但在 cakephp 中它不起作用。

SELECT * FROM users
WHERE users.Id IN (3,7,2,13)
ORDER BY FIELD(users.Id ,3,7,2,13)

我按以下顺序获取用户。这是完美的

user _id
 3
 7
 2
13

Cakephp 3

 $unique_user_id_list = (3,7,2,13);
 $id_list = '3','7','2','13';      This is string. 

$users = $this->Users->find('all',[
                'contain' => [],           
                'conditions'=>['Id IN' => $unique_user_id_list],
                'order BY FIELD'=>['Users.Id'=>$id_list]
            ]);

在此查询中,我按以下顺序获取用户

user_id
  2 
  3
  7
 13

我尝试了以下两种方法,但没有一种有效。只有“order”子句给出错误,而其他“order by field”子句没有给出错误,但无法按预期工作。

   'order'=>['Users.Id'=>$id_list]
    'order BY FIELD'=>['Users.Id'=>$id_list]

知道如何在 cakephp 3 中编写上述 sql 查询以使其工作。

最佳答案

回答这个问题 简而言之 'order' => "FIELD(id, '2', '3', '7', '13')"

详细来说,首先使用循环将数组转换为字符串。

 $id_list; 

 foreach ($unique_user_id_list as $key => $value) {
                if($check == 1){
                    $id_list = 'FIELD ( Id'.',' . "'". $value. "'";
                    $check =2;
                }
                else{
                    $id_list = $id_list . "," . "'". $value. "'";
                }

            }
            $id_list = $id_list . ")";

上面的循环将生成“FIELD(id, '2', '3', '7', '13')”

下面给出了我如何使用它的完整查询。

$users = $this->Users->find('all',[
                    'contain' => [],
                    'conditions'=>['Id IN' => $unique_user_id_list],
                    'order'=> $id_list
                ]);

关于mysql - 如何在cakephp 3中编写orderByField查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40935361/

相关文章:

Cakephp 3,更新关联的所属数据

php - 并排回显多个 div,其中包含来自 DB 的内容和容器 div 的填充宽度

mysql - Chef :了解 Chef::resource 提供?

java - 如何使用 JPA native 查询选择具有相同名称的多个列?

sql - 如何在WHERE子句中使用json列作为条件

sql - 对同一表 SQL Server 中的连续日期范围进行分组

php - CakePHP 3.0 在哪里放置查询

mysql - 使用组查询检索正确的行,但需要更多具有唯一数据的列

SQL - 正确查询按其他表中的值对项目进行排序

php - 如何在 CakePHP 3 中获取通过分页检索的记录总数?