Skip to content

Partial updates #467

Answered by houtn11
brettinternet asked this question in Q&A
Mar 17, 2025 · 1 comments · 1 reply
Discussion options

You must be logged in to vote

I usually do something like this:

type MyParams struct {
	ID       int32
	Value 	*string
}

func PartialNonNilUpdate(ctx context.Context, params MyParams) error {
        var columns ColumnList
        var myTable model.MyTable

       if params.Value != nil {
               myTable.Value = *params.Value
               columns = append(columns, MyTable.Value)
       }
       // etc..., for the rest of params

	stmt := MyTable.UPDATE(columns).
		MODEL(myTable). 
		WHERE(MyTable.ID.EQ(Int32(params.ID)))
}

To set UpdatedAt to CURRENT_TIMESTAMP I use database triggers, or sometimes myTable.UpdatedAt = time.Now().
If your params fields have the same name as your model fields, you can automate …

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@brettinternet
Comment options

Answer selected by brettinternet
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants