创建后的只读字段



我需要在创建后将模型的属性之一设置为只读。我的代码在工作,但当我尝试更新它不会抛出任何错误。

你能帮我在我们尝试更新时如何得到错误吗?

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

如果您的表没有创建,则没有任何问题

如果你创建了一个表,并且你想把model的两个属性设置为只读,如下所示:

type Test struct {
EnvID     string      `json:"env_id" gorm:"->"`                                                                                       
PartID    string      `json:"part_id" gorm:"index:depl_part;unique;priority:3;->"`
}

则必须运行以下代码

err := Client.AutoMigrate(&Test{})

现在EnvID和PartID是只读的,直到你删除->

相关内容

  • 没有找到相关文章

最新更新