Home  >  Article  >  Backend Development  >  Double brackets for where clause using "IN" at gorm

Double brackets for where clause using "IN" at gorm

WBOY
WBOYforward
2024-02-10 08:12:08880browse

在 gorm 处使用“IN”的 where 子句的双括号

php editor Xinyi brings you an important feature of gorm - the double brackets of the where clause using "IN" in gorm. This feature allows us to more conveniently query whether multiple values ​​are in a certain field, simplifies the writing of query statements, and improves the readability and maintainability of the code. By using double brackets, we can pass in a slice in the where clause, which contains the value to be queried, and gorm will automatically convert it into an "IN" clause to perform the query operation. This feature is very practical in actual development and helps us handle complex data query requirements more efficiently.

Question content

I am using where clause to update the value in the database through gorm

db.Session(&gorm.Session{FullSaveAssociations: true}).Where("id IN (?)", ids).Updates(users)

ids are part of ids and user is the structure

The problem is that I get this error

Error 1241 (21000): Operand should contain 1 column

The sql generated by gorm is this. It looks like it creates a double bracket, causing this error. But I don't know how to solve this problem

UPDATE `users` SET `status`='CANCELED',`updated_at`='2023-12-12 20:39:40.904' WHERE id IN (('066a75df-ba11-49c8-9b39-b1cce029760e','5f95f93e-94a5-46d1-86eb-dde83437ea26'))

Edit 1

I removed () from (?) and had the same effect

db.Session(&gorm.Session{FullSaveAssociations: true}).Where("id IN ?", ids).Updates(users)

UPDATE `users` SET `status`='CANCELED',`updated_at`='2023-12-12 21:18:46.537' WHERE id IN (('066a75df-ba11-49c8-9b39-b1cce029760e','5f95f93e-94a5-46d1-86eb-dde83437ea26'))

Error 1241 (21000): Operand should contain 1 column

Solution

I found the answer herehttps://github. com/go-gorm/ gorm/issues/5014 and https://gorm.io/docs/sql_builder. html#clause

Using this clause I can do something like this

query.Clauses(
            clause.Where{
                Exprs: []clause.Expression{
                    clause.Expr{
                        SQL:                "id IN ?",
                        Vars:               []interface{}{ids},
                        WithoutParentheses: true,
                    },
                },
            },
        )

The above is the detailed content of Double brackets for where clause using "IN" at gorm. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete