我无法使下面的代码表现得像它应该的那样(删除过期的记录)。简单的测试代码:
test_expire表定义:
CREATE TABLE `test_expire` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`expire` timestamp NOT NULL,
PRIMARY KEY (`id`)
);
代码:
TestExpire::deleteAll();
$record = new TestExpire();
$record->expire = new Expression("NOW() + INTERVAL 1 MONTH");
$record->save();
$record = new TestExpire();
$record->expire = new Expression("NOW() + INTERVAL 1 YEAR");
$record->save();
$records = TestExpire::find('expire > :expire', ['expire' => date('Y-m-d')])->all();
echo "Records (" . count($records) . "):\n";
foreach($records as $record) {
echo "Expire: " . $record->expire . "\n";
}
TestExpire::deleteAll("expire < NOW()");
$records = TestExpire::find('expire > :expire', ['expire' => date('Y-m-d')])->all();
echo "Records after delete 1: " . count($records) . "\n";
TestExpire::deleteAll("expire < :expire", [':expire' => date('Y-m-d G:i:s')]);
$records = TestExpire::find('expire > :expire', ['expire' => date('Y-m-d')])->all();
echo "Records after delete 2: " . count($records) . "\n";
TestExpire::deleteAll("expire < :expire", [':expire' => new Expression("NOW()")]);
$records = TestExpire::find('expire > :expire', ['expire' => date('Y-m-d')])->all();
echo "Records after delete 3: " . count($records) . "\n";
我希望所有deleteAll表达式都相同,每个表达式都不会删除记录。但最后一个确实如此。这是输出:
Records (2):
Expire: 2015-01-05 14:52:02
Expire: 2015-12-05 14:52:02
Records after delete 1: 2
Records after delete 2: 2
Records after delete 3: 0
问题是为什么会发生这种情况以及如何使其按预期工作?
答案 0 :(得分:1)
好吧,最后一个sql查询是:
DELETE FROM `test_expire` WHERE expire < 'NOW()';
而不是
DELETE FROM `test_expire` WHERE expire < NOW();
感谢您报告此错误,我在此处创建了一个问题:https://github.com/yiisoft/yii2/issues/6382
编辑:正如Yii问题跟踪器所述,参数绑定是一个pdo功能,不能将其与db表达式一起使用。