具有条件限制和顺序的cakephp查询

时间:2012-06-30 12:40:41

标签: mysql cakephp mysql-error-1064

我想使用表格created中的字段Users检索cakephp中的最后3位注册用户。

在我的控制器中我有:

$this->User->recursive = 1;
    $this->set('users',
        $this->User->find('all',
             array('conditions'=> array(
                  'limit' => 3,
                  'order' => array(
                  'created' => 'asc'
                  )
             )
         )
    )
);

运行时上面的代码返回此错误:

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 

我该怎么做才能解决错误?

6 个答案:

答案 0 :(得分:6)

尝试这样的事情:

$this->set('users', $this->User->find('all', array(
    'limit' => 3,
    'order' => 'User.created DESC',
    'recursive' => 1,
)));

答案 1 :(得分:2)

保留您的订单并限制条件数组的一侧,然后它将顺利运行。

使用以下格式:

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'
)

答案 2 :(得分:2)

您可以通过sql查询轻松选择数据:

$sql = "SELECT * FROM users where recursive =1 order by created desc limit 0,3";
$users = $this->users->query($sql);

$this->set(compact('users'));

答案 3 :(得分:1)

请尝试以下代码:

 $this->set('users', $this->User->find('all', array(
                                        'order' => 'created ASC',
                                        'limit' => 3  )
            ));

请参阅this link了解CakePHP查找条件。

答案 4 :(得分:0)

$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));

答案 5 :(得分:0)

首先限制数据时,您应该订购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
        )
    )
);