我试图用Gorm定义一个自定义连接表,并遵循文档here.

Update:我的问题是,列created_at和deleted_at从未被创建:


ERROR: column "created_at" of relation "user_books" does not exist (SQLSTATE 42703)
[1.066ms] [rows:0] INSERT INTO "user_books" ("user_id","book_isbn","created_at","deleted_at") VALUES (6,'1785041851','2024-04-02 21:54:01.082',NULL) ON CONFLICT DO NOTHING

ERROR: column "created_at" of relation "user_books" does not exist (SQLSTATE 42703)
[7.967ms] [rows:1] UPDATE "users" SET "created_at"='2024-04-02 21:46:34.3',"updated_at"='2024-04-02 21:54:01.078',"deleted_at"=NULL,"name"='MockUser' WHERE "users"."deleted_at" IS NULL AND "id" = 6

这就是我所拥有的实体.有用户,他们与书籍有多对多的关系.

type User struct {
    gorm.Model
    Name  string
    Books []Book `gorm:"many2many:user_books"`
}

type Book struct {
    ISBN  string `gorm:"primaryKey"`
    URL   string `json:"url"`
    Title string `json:"title"`
}

type UserBooks struct {
    UserId    int    `gorm:"primaryKey"`
    BookISBN  string `gorm:"primaryKey"`
    CreatedAt time.Time
    DeletedAt gorm.DeletedAt
}

这就是我自动迁移表的方式:

err = db.AutoMigrate(&User{}, &Book{})
err = db.SetupJoinTable(&User{}, "Books", &UserBooks{})

这就是我保存实体的方法:

var book Book
cfg.Database.Table("books").Find(&book, isbn)
user.Books = append(user.Books, book)
err = cfg.Database.Table("users").Save(&user).Error

推荐答案

SetupJoinTable只设置表 struct ,其中只包含必要的关键字段,以建立表之间的关系.

所以你也需要为你的UserBooks表运行AutoMigrate.

err = db.AutoMigrate(&User{}, &Book{}, &UserBooks{})

Go相关问答推荐

如何创建两个连接的io.ReadWriteClosers以用于测试目的

使用恶意软件 scanner (ClamAV)时的Google云存储桶上传文件验证

追加一个字节数组的分配比2个字节数组的分配要少得多

从Kafka到Clickhouse的实时消费数据

Go协议缓冲区导入问题

更改位置级别和时间戳零点Golang

即使HTTP服务器正在使用GO和Protobuf、SQL Server启动,请求也不返回结果

mockgen不创建模拟

如何在Golang中覆盖404

Kperf 构建失败

使用Goldmark在golang中添加ChildNode会导致堆栈溢出

是否可以在调试期间在 VSCode 中预览 github.com/shopspring/decimal 值?

使用 GO 在侧 tar 文件中提取 tar 文件的最快方法

Golang prometheus 显示自定义指标

即使一个测试用例失败,如何运行所有测试用例

具有相同提前返回语句的函数的不同基准测试结果

Go 使用 struct 作为接口而不实现所有方法

如何在 Unmarshal 中使用泛型(转到 1.18)

Go Flag 用法 描述 包含 Word 值

为什么 template.ParseFiles() 没有检测到这个错误?