如何在yii2中的activerecord查询中使用变量
如何将以下内容转换为yii2中的活动记录样式如何在yii2中的activerecord查询中使用变量,activerecord,yii2,Activerecord,Yii2,如何将以下内容转换为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 mon
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)
Yii2有一个
表达式类来帮助处理这类事情()
在您的情况下,它看起来像:
Customers::find()
->where(['>=', 'created_at', new \yii\db\Expression('(CURDATE() - INTERVAL ' . $p . ')'))
->orderBy('id DESC');
代替传递字符串
您可以将$p作为参数传递
Customers::find()
->where( 'created_at >=(CURDATE() - INTERVAL :p' ), [':p'=>$p])
->orderBy('id DESC');