【问题标题】:CakePHP - How to use SQL NOW() in find conditionsCakePHP - 如何在查找条件中使用 SQL NOW()
【发布时间】:2012-10-24 14:57:55
【问题描述】:

在我的条件下,我无法使用 SQL 函数 NOW() 来执行任何查找操作。

我正在有效地尝试构建一个查找查询:

所需的 SQL:

WHERE (NOW() BETWEEN Promotion.start AND Promotion.end) AND Promotion.active = 1

我尝试了很多组合,但无论我在条件中使用 NOW() 时做什么,它都不起作用,因为 Cake 构建的查询在模型字段周围放置了 ' 引号,因此 MySQL 将它们解释为一个字符串。

$this->find('all', array(
    'conditions' => array(
        '(NOW() BETWEEN ? AND ?)' => array('Promotion.start', 'Promotion.end'),
        'Promotion.active' => 1
    )
));

CakePHP 创建的 SQL:

注意 BETWEEN() 中模型字段周围的单引号,因此它们被视为字符串。

WHERE (NOW() BETWEEN 'Promotion.start' AND 'Promotion.end') AND `Promotion`.`active` = '1'

这也不行。

$this->find('all', array(
    'conditions' => array(
        'NOW() >=' => 'Promotion.start',
        'NOW() <=' => 'Promotion.end',
        'Promotion.active' => 1
    )
));

我知道为什么这些解决方案不起作用。这是因为模型字段仅当它们是条件中的数组键而不是数组值时才被处理。

我知道如果我把整个 BETWEEN() 条件作为一个字符串,我可以让它工作:

$this->find('all', array(
    'conditions' => array(
        'NOW() BETWEEN Promotion.start AND Promotion.end',
        'Promotion.active' => 1
    )
));

同样问题的另一个例子是,比较容易理解:

所需的 SQL:

WHERE Promotion.start > NOW() AND Promotion.active = 1

所以我试试这个:

$this->find('all', array(
    'conditions' => array(
        'Promotion.start >' => 'NOW()',
        'Promotion.active' => 1
    )
));

同样它不起作用,因为 Cake 在 NOW() 部分周围加上了 ' 引号。

CakePHP 创建的 SQL:

WHERE `Promotion`.`start` > 'NOW()' AND `Promotion`.`active` = '1''

【问题讨论】:

    标签: cakephp cakephp-2.0


    【解决方案1】:
    $this->find('all', array(
        'conditions' => array(
            'NOW() BETWEEN Promotion.start AND Promotion.end',
            'Promotion.active' => 1
        )
    ));
    

    【讨论】:

    • 这里到底要注入什么?没有用户输入。
    • 如果是用户数据,您将从请求对象获取数据,例如:$this->request->data['Promotion']['start']。在我展示的示例代码中,Promotion.start 和 Promotion.end 只是查询中使用的字段名称,没有用户输入。
    【解决方案2】:

    最好不要使用 NOW() 作为它的函数,并且函数不使用索引。更好的解决方案是:

    $this->find('all', array(
        'conditions' => array(
            "'" . date('Y-m-d') . "' BETWEEN Promotion.start AND Promotion.end",
            'Promotion.active' => 1
        )
    ));
    

    【讨论】:

    • 函数不使用索引是什么意思?
    • MySQL 不支持基于函数的索引。当查询包含函数(或表达式)时,它不能使用索引。它必须进行全表扫描。尝试使用解释扩展,看看它不使用哪些索引;-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多