创建后 Gorm 只读字段

标签 go go-gorm

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

你能帮我解决当我们尝试更新时如何出错吗?

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

最佳答案

如果你的表没有创建你没有任何问题

如果您的表已创建并且您想将模型的两个属性设为只读,如下所示:

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 是只读的,直到您从 GORM 中删除 -> 并运行顶级代码。

关于创建后 Gorm 只读字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72724841/

相关文章:

parsing - X 后响应退出

go - 具有不同“必填”字段的POST和GET模型

mysql - 如何防止gorm将自定义整数类型转换为字符串?

sql - 如何为多列创建唯一约束?

postgresql - 在 Gorm 模型中添加整数数组作为数据类型

用于 golang 中非特权 ICMP ping 的 go-ping 库

go - 有人可以解释一下为什么 "curl: (7) Failed to connect to 127.0.0.1 port 2000: Connection refused"吗?

function - Go 的 struct 方法在调用中抛出太多参数

go - gorm检查多对多关系是否重复

go - 运行时错误 : invalid memory address or nil pointer dereference (golang-gorm) for POST Request