[英]How to create a table with slices in columns
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. 使用gorm为它创建表时,没有“项目”或“类别”列。
What am i missing?
我想念什么?
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. 由于SQL中不支持数组的列类型(至少是SQL的大多数版本),gorm不会为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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.