How to create read only Fields
The document you expected this should be explained
Expected answer
type Product struct {
gorm.Model
ProductID int gorm:"primaryKey"
Code string gorm:"->"
Price uint gorm:"->"
}
// TestSuite is code to all tests, independent of database
func TestSuite(db *gorm.DB) { // Migrate the schema
db.AutoMigrate(&Product{})
// Create
db.Debug().Create(&Product{Code: "D42", Price: 100, ProductID: 1})
// Read
var product Product
// db.Debug().First(&product, 1) // find product with integer primary key
db.Debug().First(&product, "product_id = ?", 1) // find product with code D42
// Update - update product's price to 200
err := db.Debug().Model(&product).Update("Price", 200).Error
if err != nil {
fmt.Println(err.Error())
}
// Update - update multiple fields
err = db.Debug().Model(&product).Updates(Product{Price: 200, Code: "F42"}).Error // non-zero fields
if err != nil {
fmt.Println(err.Error())
}
db.Debug().First(&product, "product_id = ?", 1)
err = db.Debug().Model(&product).Updates(map[string]interface{}{"Price": 200, "Code": "F42"}).Error
if err != nil {
fmt.Println(err.Error())
}
// Delete - delete product
db.Debug().Delete(&product, 1)
}
This one should raise error on update.
Comment From: a631807682
This needs to be handled by yourself. In addition to the fields declared in updates, we also need to handle with custom hooks and custom type fields. We decide on behalf of the user whether to report an error or not.