【问题标题】:CakePHP complex find conditionsCakePHP 复杂的查找条件
【发布时间】:2012-08-27 18:20:31
【问题描述】:

例如,我有一个包含 fromH 和 toH 字段的 Store 模型,我想从数据库中检索在给定时间 (@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 中实现这个查询,条件数组看起来如何?我想做蛋糕风格。

【问题讨论】:

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


    【解决方案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);
    

    【讨论】:

    • 当我尝试运行此查询时,我收到以下错误:错误:SQLSTATE[42S22]:找不到列:1054 'where 子句'中的未知列'15' - “15”是@t
    【解决方案2】:

    您可以使用以下 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')
                )
            ),
        )
    ));
    

    【讨论】:

    • 可能也想修复两者之间的双重问题。
    猜你喜欢
    • 2012-04-12
    • 2012-12-03
    • 2012-10-21
    • 1970-01-01
    • 2013-04-14
    • 1970-01-01
    • 2014-03-22
    • 2017-07-06
    • 2011-10-22
    相关资源
    最近更新 更多