How to create a table with slices in columns

穿精又带淫゛_ 提交于 2019-12-20 07:45:25

问题


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. What am i missing?


回答1:


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)


来源:https://stackoverflow.com/questions/55214595/how-to-create-a-table-with-slices-in-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!