Search code examples
gogo-gorm

Creating custom join table with Gorm


I'm trying to define a custom join table with Gorm and followed the docs here.

Update: My problem is that the columns created_at and deleted_at get never created:


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

That are the entities I have. There are users and they have a many-to-many relation to books.

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
}

And this is how I auto-migrate the table:

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

And that how I save the entities:

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

Solution

  • SetupJoinTable only sets up the table structure with only the necessary key fields to establish the relationships between the tables.

    So you need to run AutoMigrate for your UserBooks table also.

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