cakePHP复杂查找查询

时间:2012-03-28 17:39:21

标签: php sql cakephp cakephp-1.3

如何使用以下条件在cakePHP中构建find()查询:

Find where 
MyModel.x = 1 and MyModel.y = 2 OR 
MyModel.x = 1 and MyModel.y value does not exist (or is equal to empty string)

有人可以告诉我如何构建这样的查询查询吗?

2 个答案:

答案 0 :(得分:4)

我会给你一些指示,但你需要尝试这样做,因为它非常基本,而且练习总是好的。

蛋糕中的基本发现是

$this->ModelName->find('all');

这是默认形式的SELECT * from model_names(约定是多个表名的单数ModelName - model_names

添加条件:

$this->ModelName->find('all', array('conditions' => array('ModelName.x' => 1));

添加AND条件

$this->ModelName->find('all', array('conditions' => array(
   'ModelName.x' => 1, 'ModelName.y' => 2
));

添加OR条件

$this->ModelName->find('all', array('conditions' => array(
   'OR' => array(
      'ModelName.x' => 1, 'ModelName.y' => 2
    )
));

将两者结合起来

$this->ModelName->find('all', array('conditions' => array(
   'ModelName.y is not' => null,
   'OR' => array(
      'ModelName.x' => 1, 'ModelName.y' => 2
    )
));

// where y is not null and (x = 1 or y = 2) 

http://book.cakephp.org/1.3/view/1030/Complex-Find-Conditions

(顺便说一下,我确信会有用户给你准确的答案,所以请把我的答案作为参考:))

答案 1 :(得分:3)

$this->MyModel->find('all', array('conditions' => array(
    'OR' => array(
         array(
             'MyModel.x' => 1,
             'MyModel.y' => 1
         ),
         array(
             'MyModle.x' => 1,
             'OR' => array(
                  array('MyModel.y' => NULL),
                  array('MyModel.y' => '')
             )
         )
    )
)));