示例代码:

// 构建要删除的条件

conditions := []struct {
    GoodsID      string
    PurchaseType int
}{
    {"33B3AFBAF000", 1},
    {"33B3AFBAF001", 1},
}
// 初始 where 条件
query := db.Where("buyer_id = ?", "test")
// 动态构建 OR 条件
for _, condition := range conditions {
    query = query.Or("goods_id = ? AND purchase_type = ?", condition.GoodsID, condition.PurchaseType)
}
// 执行删除操作
query.Delete(&Cart{})

上面代码最终生成的sql是 where buyer_id = "aaaa" OR (goods_id = 'xxx' and purchase_type=2) OR (xxxxx)

我期望得到是:

where buyer_id = "aaaa" AND ( (goods_id = 'xxx' and purchase_type=2) OR (xxxxx))

怎么写才能实现上面的优先级?

The document you expected this should be explained

Expected answer

Comment From: ivila

@JaneMeary change your code to the following:

        conditions := []struct {
                GoodsID      string
                PurchaseType int
        }{
                {"33B3AFBAF000", 1},
                {"33B3AFBAF001", 1},
        }
        // 初始 where 条件
        query := db.Where("buyer_id = ?", "test")

        sub_query := db
        // 动态构建 OR 条件
        for _, condition := range conditions {
                sub_query = sub_query.Or("goods_id = ? AND purchase_type = ?", condition.GoodsID, condition.PurchaseType)
        }
        query = query.Where(sub_query)
        // 执行删除操作
        err := query.Delete(&User{}).Error

It works with version v1.25.9, try testing the codes with your verison first.

Comment From: JaneMeary

@JaneMeary change your code to the following:

```go conditions := []struct { GoodsID string PurchaseType int }{ {"33B3AFBAF000", 1}, {"33B3AFBAF001", 1}, } // 初始 where 条件 query := db.Where("buyer_id = ?", "test")

    sub_query := db
    // 动态构建 OR 条件
    for _, condition := range conditions {
            sub_query = sub_query.Or("goods_id = ? AND purchase_type = ?", condition.GoodsID, condition.PurchaseType)
    }
    query = query.Where(sub_query)
    // 执行删除操作
    err := query.Delete(&User{}).Error

```

It works with version v1.25.9, try testing the codes with your verison first.

非常感谢,这样是可以的。