问题
I want to retrieve the last 3 registered users in cakephp using the field created
in table 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?
回答1:
Try something like this:
$this->set('users', $this->User->find('all', array(
'limit' => 3,
'order' => 'User.created DESC',
'recursive' => 1,
)));
回答2:
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'
)
回答3:
You can easily also select your data by this is sql query :
$sql = "SELECT * FROM users where recursive =1 order by created desc limit 0,3";
$users = $this->users->query($sql);
$this->set(compact('users'));
回答4:
Please try code like given below:
$this->set('users', $this->User->find('all', array(
'order' => 'created ASC',
'limit' => 3 )
));
Please refer to this link for CakePHP find conditions.
回答5:
$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));
回答6:
When you limit the data first you should order DESC or ASC
. Another easy way that works fine
$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
)
)
);
来源:https://stackoverflow.com/questions/11274146/cakephp-query-with-conditions-limit-and-order