MySQL 带有条件限制和顺序的 cakephp 查询
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11274146/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
cakephp query with conditions limit and order
提问by ifunk
I want to retrieve the last 3 registered users in cakephp using the field createdin table Users.
我想使用createdtable 中的字段检索 cakephp 中的最后 3 个注册用户Users。
In my controller I have:
在我的控制器中,我有:
$this->User->recursive = 1;
$this->set('users',
$this->User->find('all',
array('conditions'=> array(
'limit' => 3,
'order' => array(
'created' => 'asc'
)
)
)
)
);
The code above when run returns this error:
运行时上面的代码返回此错误:
Syntax error or access violation: 1064 You have an error in your SQL
syntax; check the manual that corresponds to your MySQL server
version for the right syntax to use near 'order = ('asc')' at line
What must I do to resolve the error?
我必须怎么做才能解决错误?
回答by ifunk
Try something like this:
尝试这样的事情:
$this->set('users', $this->User->find('all', array(
'limit' => 3,
'order' => 'User.created DESC',
'recursive' => 1,
)));
回答by Ajay
Keep your order and limit out side of condition array then it will work smoothly.
保持您的订单并限制条件数组的一侧,然后它将顺利运行。
Use this format:
使用这种格式:
array(
'conditions' => array('Model.field' => $thisValue), //array of conditions
'recursive' => 1, //int
'fields' => array('Model.field1', 'DISTINCT Model.field2'),
'order' => array('Model.created', 'Model.field3 DESC'),
'group' => array('Model.field'), //fields to GROUP BY
'limit' => n, //int
'page' => n, //int
'offset' => n, //int
'callbacks' => true //other possible values are false, 'before', 'after'
)
回答by Ajay
You can easily also select your data by this is sql query :
您还可以通过以下 sql 查询轻松选择数据:
$sql = "SELECT * FROM users where recursive =1 order by created desc limit 0,3";
$users = $this->users->query($sql);
$this->set(compact('users'));
回答by Er. Anurag Jain
回答by Haruna Akhmad
$dashreport = $this->Task->find('all', array('conditions' =>
array('Task.throttle' => "Report", 'Task.status' => Null, 'Task.userid' => $this->Session->read('userid')),'order'=>array('Task.id DESC')
,'limit'=> 4));
回答by A.A Noman
When you limit the data first you should order DESC or ASC. Another easy way that works fine
当您首先限制数据时,您应该订购DESC or ASC. 另一种工作正常的简单方法
$this->set('datas',
$this->Your_Model_Name->find('all',
array (
'conditions' => array('Site_id' => $site_name), //conditions here
'fields' => array('Date_time','Ac_1_Status','Tempin'),
'order' => array('id' => 'desc'), // id desc or asc
'limit' => 15
)
)
);

