Home >Backend Development >Golang >golang gorm update and return

golang gorm update and return

PHPz
PHPzforward
2024-02-05 22:06:12597browse

golang gorm 更新并返回

Question content

In my golang project, I use gorm, I need to make an upsert query using return clause to get the modifications from the query value after. I can do an upsert, but I don't know how to connect the return clause to it. The table name is counters, and the code is as follows:

te := struct {
        name string //key column
        counter int
    }{
        name: "name_to_update",
        counter: 2,
    }

db.
    //model(te).
    clauses(
        //clause.returning{columns: []clause.column{{name: "counter"}}},
        clause.onconflict{
            columns: []clause.column{{name: "name"}}, // key column
            doupdates: clause.assignments(map[string]interface{}{
                "counter": gorm.expr("counters.counter + ?", 1),
            }),
        },
    ).create(&te)

The generated sql query is:

INSERT INTO "counters" ("counter", "name") VALUES (0, "name_to_update") ON CONFLICT ("name") 
DO UPDATE SET "counter"=counters.counter + 1 RETURNING "name" //I need updated counter value here, not name

So the counter is updated, which is no problem, but when I need the updated value of the counter, it returns the key column (in the return). Any ideas how to fix it? Thanks


Correct answer


I'm not sure if the anonymous structure is causing the problem.

Also, it's not clear from your code where the table name - "counters" - comes from.

I've tried your solution - but using a dedicated structure for the model - and it works great.

type counter struct {
    name    string `gorm:"primarykey"`
    counter int
}

...

counter := counter{name: "name_to_update", counter: 2}

    db.
        clauses(
            clause.returning{columns: []clause.column{{name: "counter"}}},
            clause.onconflict{
                columns: []clause.column{{name: "name"}},
                doupdates: clause.assignments(map[string]interface{}{
                    "counter": gorm.expr("counters.counter + ?", 1),
                }),
            },
        ).create(&counter)

    fmt.println(counter.counter)

The above code generates the following sql

INSERT INTO "counters" ("name","counter") VALUES ('name_to_update',10) ON CONFLICT ("name") DO UPDATE SET "counter"=counters.counter + 1 RETURNING "counter"

And counter.counter has the correct updated value.

The above is the detailed content of golang gorm update and return. 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