【问题标题】:Yii2 bind param to the raw sql statement for the IN fieldYii2 将参数绑定到 IN 字段的原始 sql 语句
【发布时间】:2015-11-18 16:29:00
【问题描述】:

当我在 Yii2 中使用 bindParam 时:

$arr = [1,3];
$str = implode(' ,', $arr);
Yii::$app->db->createCommand('DELETE FROM article_tag WHERE article_id=:id AND tag_id IN (:str)')
        ->bindValue(':id', $this->id)
        ->bindValue(':str', $str)
        ->execute();

如果我将 str 绑定到 IN 字段,原始 sql 似乎变成了

SQLSTATE[22007]: Invalid datetime format: 1292 Truncated incorrect DOUBLE value: '1 ,3'
The SQL being executed was: DELETE FROM article_tag WHERE article_id=13 AND tag_id IN ('1 ,3')

它告诉我这里的双精度值不正确。我猜这是因为它在 sql 中添加了单引号。我该如何处理??

【问题讨论】:

    标签: sql yii2 dao


    【解决方案1】:

    代码可以重构为:

    Yii::$app
        ->db
        ->createCommand()
        ->delete('article_tag', ['article_id' => $this->id, 'tag_id' => $arr])
        ->execute();
    

    使用框架功能,更复杂的查询需要编写原始 SQL。

    请参阅this question 以了解参数是如何自动绑定的。 Here你可以看到如何在where语句中指定条件。

    在大多数情况下,最好创建ActiveRecord 并使用ActiveQuery 来构建查询。

    【讨论】:

    • 这里会删除多条记录吗?我使用 IN 因为我想使用一个 sql 删除多条记录。
    • @tyan 是的,当您在where 语句中将数组作为值传递给键值对时,它将自动转换为IN 语句。见provided link,有数组和IN的例子。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-20
    • 2015-09-08
    • 2012-10-15
    • 2021-01-26
    • 2018-11-15
    • 1970-01-01
    相关资源
    最近更新 更多