如何在yii2中将以下内容转换为活动记录样式?
SELECT *
FROM orders
WHERE created_at >= (CURDATE() - INTERVAL 11 MONTH)
ORDER BY id DESC
我尝试过:
switch ($period) {
case 'y':
$p = "12 month";
break;
case 'm':
$p = "1 month";
break;
case 'w':
$p = "7 days";
break;
case 'd':
$p = "1 days";
break;
}
Customers::find()
->where('>=', 'created_at', (CURDATE() - INTERVAL $p))
->orderBy('id DESC');
但我明白了:
syntax error, unexpected '$p' (T_VARIABLE)
答案 0 :(得分:4)
传递字符串
你可以将$ p作为参数传递
Customers::find()
->where( 'created_at >=(CURDATE() - INTERVAL :p' ), [':p'=>$p])
->orderBy('id DESC');
答案 1 :(得分:3)
Yii2有一个Expression
课程来帮助处理这些事情(doc here)。
在你的情况下,它看起来像:
Customers::find()
->where(['>=', 'created_at', new \yii\db\Expression('(CURDATE() - INTERVAL ' . $p . ')'))
->orderBy('id DESC');