在Cakephp中查找sql​​查询查找方法

时间:2014-11-28 16:47:21

标签: mysql cakephp-2.3

我有以下SQL查询:

SELECT * FROM pm_management.system_tasks 
  WHERE eq_model = 'D9 L' and pm_type = 'H' and 
     ((equipment = '5164' and main_systems_id = 1) or 
      (equipment = 'TODOS' and main_systems_id <> 1));

我想在Cakephp find()方法中编写该查询。我尝试了以下但结果不是预期的。

$sys_content = $this->SystemTask->find('all', array(
     'conditions' => array('AND' => array(
           'eq_model' => 'D9 L',
           'pm_type' => 'H',
              'OR' => array(
                  'AND' => array(
                     'equipment' => '5164',
                     'main_systems_id' => '1'
                   ),
                  'AND' => array(
                     'equipment' => 'TODOS',
                     'main_systems_id' => '<> 1'
                   )
                )
           ))
        ));

提前感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

使用下一个条件。当你写条件时要注意你不能在单个哈希(= array)中有两次相同的键。所以第二个AND覆盖了你的状况。由于AND是默认值,您可以像我在下面的代码中那样删除它,

$sys_content = $this->SystemTask->find('all', array(
 'conditions' => array(
       'eq_model' => 'D9 L',
       'pm_type' => 'H',
          'OR' => array(
              array(
                 'equipment' => '5164',
                 'main_systems_id' => '1'
               ),
              array(
                 'equipment' => 'TODOS',
                 'main_systems_id' => '<> 1'
               )
            )
       )
    ));

或用[&#39; AND&#39; =&GT; ...]附加数组()。

$sys_content = $this->SystemTask->find('all', array(
 'conditions' => array('AND' => array(
       'eq_model' => 'D9 L',
       'pm_type' => 'H',
          'OR' => array(
              array(
                'AND' => array(
                   'equipment' => '5164',
                   'main_systems_id' => '1'
                )),
              array(
                'AND' => array(
                   'equipment' => 'TODOS',
                   'main_systems_id' => '<> 1'
               ))
            )
       ))
    ));

答案 1 :(得分:0)

实际上,您可以使用$this->Model->query($yourQuery)来实现此目的。即使不推荐也是如此。但是最好没有头痛将它转换为CakePHP查找。