乐闻世界logo
搜索文章和话题

How do I set an integer column to null, and update the model in-memory in Gorm?

1个答案

1

When using Gorm, if you want to set an integer column to NULL and update the model in memory, you should follow several key steps. First, ensure that the field in your model can accept NULL values. Typically, this is achieved by using the sql.NullInt64 type instead of the standard int type. This is because in Go, basic integer types (such as int, int32, int64, etc.) cannot be set to NULL.

Here's a simple example to illustrate this process:

1. Define the Model

First, define the model, ensuring that you use sql.NullInt64 for integer fields that may need to be set to NULL.

go
package main import ( "database/sql" "gorm.io/driver/sqlite" "gorm.io/gorm" ) type Product struct { gorm.Model Name string Quantity sql.NullInt64 // Use sql.NullInt64 instead of int }

2. Initialize the Database and Migrate the Model

go
func main() { db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{}) if err != nil { panic("failed to connect database") } // Auto-migrate to match the model structure db.AutoMigrate(&Product{}) }

3. Update the Field and Set to NULL

To set the Quantity to NULL in the database, you need to use the sql.NullInt64 structure and set Valid to false.

go
func main() { // Assume there is an existing Product record that we want to set Quantity to NULL db, _ := gorm.Open(sqlite.Open("test.db"), &gorm.Config{}) var product Product db.First(&product, 1) // Assume we are updating the product with ID 1 // Set Quantity to NULL product.Quantity = sql.NullInt64{Int64: 0, Valid: false} db.Save(&product) // Save the changes }

In this example, we first retrieve an existing Product record. Then we set Quantity to 0 and mark Valid as false, indicating that this value should be treated as NULL. Finally, we use the Save method to commit the changes to the database.

This ensures that the model in memory is updated to NULL, allowing your application logic to handle this case correctly. In actual business logic, you should also consider error handling and transactions to ensure data consistency and integrity.

2024年8月12日 17:22 回复

你的答案