CakePHP复杂查找条件

时间:2012-09-02 23:41:28

标签: cakephp cakephp-1.3 cakephp-2.0 cakephp-2.1 cakephp-1.2

例如,我有一个包含来自H和toH字段的商店模型,我想从数据库中检索在给定时间内打开的商店(@t)。

SQL查询看起来像这样

select *
from store 
where 
( fromH < toH and @t between fromH and toH ) or
( fromH > toH and 
     (@t between fromH and 24 OR
     (@t between 1 and toH )
)

如何在cakephp中实现此查询,条件数组如何显示?我想做蛋糕风格。

2 个答案:

答案 0 :(得分:1)

您可以使用以下CakePHP等效选择查询来尝试:

<?php $this->Store->find('all', array(
    'conditions' => array(
        'OR' => array(
            'AND' => array(
                'fromH < ' => 'toH',
                $t.' BETWEEN ? AND ?' => array('fromH', 'toH')
            )
        ),
    'AND' => array(
            'fromH > ' => 'toH',
            'OR' => array(
                $t.' BETWEEN ? AND ?' => array('fromH', '24'),
                $t.' BETWEEN ? AND ?' => array('1', 'toH')
            )
        ),
    )
));

答案 1 :(得分:1)

@Arun Jain给出的答案与解决方案非常接近,但由于OR状态的规则必须各自为其自己的数组,因为它们的键值是相同的。如果你

print_r($conditions);

你会发现你的一些规则遗失了。

我认为以下解决方案适合您。

$conditions = array(
    'conditions' => array(
        'OR' => array(
            array(
                'AND' => array(
                    'fromH <' => 'toH',
                    @t.' BETWEEN ? AND ?' => array('fromH','toH')
                 )
            ),
            array(
                'AND' => array(
                    'fromH >' => 'toH',
                    'OR' => array(
                        @t.' BETWEEN ? AND ?' => array('fromH','24'),
                        @t.' BETWEEN ? AND ?' => array('1','toH')
                    )
                )
            )
        )
    )
);

$this->Strore->find('all',$conditions);