Yii2 createCommand 带参数

Yii2 createCommand with params

我需要在数据库中计算我的购物车商品,没有模型的购物车商品。像这样尝试:

$id = Yii::$app->request->post('id');
$total = Yii::$app->db->createCommand('SELECT COUNT(*) FROM cart_items WHERE user_id="'.$id.'"')->queryScalar();

Return 0,但有 2 行。

$total = Yii::$app->db->createCommand('SELECT COUNT(*) FROM cart_items WHERE user_id="19"')->queryScalar();

Return 2.

如何将我的参数与 post 数据正确绑定?

更新:

public function beforeAction($action) {
        $this->enableCsrfValidation = false;
        if (parent::beforeAction($action)){
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return true;
        }
        return false;
    }
public function behaviors()
    {
        return [            
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'checkout' => ['post','get'],
                ],
            ],
        ];
    }

您可以使用 bindValues()

  $total = Yii::$app->db->createCommand('SELECT COUNT(*) 
         FROM cart_items WHERE user_id=:id')
    ->bindValues([':id'=>$id)
    ->queryScalar();