I need to make one of the property of model as read only after create. My code in working but when I try to update It will not throw any error.
Could you please help me in how to get error when we try to Update?
package main
import (
"fmt"
"gorm.io/gorm"
)
type Product struct {
gorm.Model
ProductID int `gorm:"primaryKey"`
Code string `gorm:"->;<-:create"`
Price uint
}
// TestSuite is code to all tests, independent of database
func TestSuite(db *gorm.DB) { // Migrate the schema
db.AutoMigrate(&Product{})
// Create
db.Create(&Product{Code: "D4222", Price: 1000, ProductID: 3})
// Read
var product Product
db.First(&product, "product_id = ?", 3) // find product with product_id 2
fmt.Println("Product Code After Creation: ", product.Code)
fmt.Println("Product Price After Creation: ", product.Price)
//Update
err := db.Model(&product).Where("product_id = ?", 3).Updates(Product{Price: 400, Code: "F42"}).Error
if err != nil {
fmt.Println(err)
}
// Read after update
var updateProd Product
db.First(&updateProd, "product_id = ?", 3) // find product with product_id 2
fmt.Println("Product Code After Update: ", updateProd.Code)
fmt.Println("Product Price After Update: ", updateProd.Price)
// Delete - delete product
db.Unscoped().Delete(&updateProd, 3)
}
Output:
Product Code After Creation: D4222
Product Price After Creation: 1000
Product Code After Update: D4222
Product Price After Update: 400