How to create a table with slices in columns

2020-05-10 09:17发布

I have a model that looks like this:

type Inventory struct {
    gorm.Model
    LocationID string
    Items      []Item //this is a slice of structs
    Categories []Category //this is a slice of structs
}

When I create a table for it using gorm, I don't have the columns for Items or Categories. enter image description here What am i missing?

1条回答
男人必须洒脱
2楼-- · 2020-05-10 09:35

Since arrays are not supported column types in SQL—most versions of SQL at least—gorm will not create columns for fields of type slice.

You can, however, create the relationship structure you are after using an association. In this case either the has-many or many-to-many would be appropriate (I can't tell from this example, though likely has-many).

These work by creating separate tables for these nested objects. In the has-many relationship, a separate table for items and categories would be created, each with a foreign key reference to the inventory table. The many-to-many case is similar but uses a join table rather than a simple foreign key.

For example (with has-many):

type Inventory struct {
    gorm.Model
    LocationID string
    Items      []Item //this is a slice of structs
    Categories []Category //this is a slice of structs
}

type Item struct {
    // ...
    InventoryId uint
}

type Category struct {
    // ...
    InventoryId uint
}

db.Model(&inventory).Related(&items)
db.Model(&inventory).Related(&categories)
查看更多
登录 后发表回答