Your Question

type Print struct {
    gorm.Model
    OwnerID   uint    `gorm:"not null;index"`
    OwnerType string  `gorm:"type:varchar(32);not null;index"`
}

printIDs := make([]uint, 0)

if e := db.Model(&Print{}).Where(
    "owner_type = ? AND owner_id IN ?", "cart_products", ids,
).Pluck("id", &printIDs).Error; e != nil {
    return e
}
// Error 1064 (42000): You have an error in your SQL syntax; 
// check the manual that corresponds to your MySQL server version 
// for the right syntax to use near '?) AND `prints`.`deleted_at` IS NULL' at line 1

Debug 来看一切正常:

[0.203ms] [rows:0] SELECT `id` FROM `prints` WHERE (owner_type = 'cart_products' AND owner_id IN 190293163808653315) AND `prints`.`deleted_at` IS NULL

The document you expected this should be explained

https://gorm.io/zh_CN/docs/advanced_query.html#Pluck

Expected answer

这是为何?

Comment From: congjunhua

换成 map 条件则不再报错:

if e := db.Model(&Print{}).Where(
    // "owner_type = ? AND owner_id IN ?", "cart_products", ids,
        map[string]any{"owner_type": "cart_products", "owner_id": ids},
).Pluck("id", &printIDs).Error; e != nil {
    return e
}

看来问题出在字符串中的❓。

Comment From: saeidee

When you use IN you should provide a slice as a parameter and the IN keyword should be within the parentheses something like this.

err := db.Model(&Print{}).
    Where("owner_type = ? AND owner_id IN (?)", "cart_products", ids).
    Pluck("id", &printIDs).Error

Comment From: congjunhua

When you use IN you should provide a slice as a parameter and the IN keyword should be within the parentheses something like this.

go err := db.Model(&Print{}). Where("owner_type = ? AND owner_id IN (?)", "cart_products", ids). Pluck("id", &printIDs).Error

不对吧?

文档中没有括号的写法,你这个括号的写法是哪里来的,其他地方我也是根据文档中不带括号的写法来写的,也没有报错。

// IN
db.Where("name IN ?", []string{"jinzhu", "jinzhu 2"}).Find(&users)
// SELECT * FROM users WHERE name IN ('jinzhu','jinzhu 2');

Gorm Pluck报Error 1064 (42000): You have an error in your SQL syntax错误

Comment From: saeidee

Here is the playground link https://github.com/go-gorm/playground/pull/622, I have added both cases. Please have a look and try to change the way it gives errors, so we can reproduce the issue.