Yii2:我可以在连接中将数组绑定到 IN() 条件吗?

Yii2 : Can I bind an array to an IN() condition in join?

我会尝试下面的查询,但不确定是否可以防止 sql 注入?

        $status = [1, 2, 3];
        $param = implode(', ', $status);

        $rows = (new \yii\db\Query())
            ->select('*')
            ->from('user')
            ->leftJoin('post', "post.user_id = user.id AND post.some_column = $value AND post.status IN ($param)");
            ->all();

return expected results but may be occur sql injection. My IN condition look like is IN (1, 2, 3)

        $rows = (new \yii\db\Query())
            ->select('*')
            ->from('user')
            ->leftJoin('post', "post.user_id = user.id AND post.some_column = :sid AND post.status IN (:param)", [':param' => $param, ':sid' => $value]);
            ->all();

only compare first element in array because is look like this IN ('1, 2, 3') its consist single string not check second element in array only work on first element.

我在下面参考 link 但不知道如何实现此条件。

Can I bind an array to an IN() condition?

请给出如何在 join(PDO/Yii2/mysql) 的 On 部分使用 IN() Condition 的解决方案。

Yii2 可以通过将条件作为数组传递来创建参数化 IN 条件,即:

['post.status' => $status]

但是,如 Yii guide:

中所述,将连接条件转换为数组格式将不起作用

Note that the array format of where() is designed to match columns to values instead of columns to columns, so the following would not work as expected: ['post.author_id' => 'user.id'], it would match the post.author_id column value against the string 'user.id'. It is recommended to use the string syntax here which is more suited for a join:

'post.author_id = user.id'

由于您使用的是 INNER JOIN,因此将连接条件放在 WHERE 而不是 ON 中的结果在句法上将是相同的,如 INNER JOIN condition in WHERE clause or ON clause?. For readability and ease of maintenance 中所述,您可以在连接条件中保留表列的比较:

$rows = (new \yii\db\Query())
        ->select('*')
        ->from('user')
        ->innerJoin('post', 'post.user_id = user.id')
        ->where(['post.some_column' => $value, 'post.status' => $status])
        ->all();

基于this issue

        $rows = (new \yii\db\Query())
        ->select('*')
        ->from('user')
        ->leftJoin('post', ['post.user_id' => new \yii\db\Expression('user.id'), 'post.some_column' => $sid, 'post.status' => $statuesArray]);
        ->all();