简体   繁体   English

如何使用列中的切片创建表

[英]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.

相关问题 如何创建表,其中第一个表中的列是另一个表中的字段? - How to create table where columns in first table are fields in another table? 如何用其他表中的值命名的列创建表 - How to create a table with columns named after values in other table 如何从 json 表中创建具有多列的新表 - How to create new table with multiple columns from json table 如何在 Postgres 中为表中的虚拟列创建数据库链接? - How to Create DB links in Postgres for Virtual Columns in a table? 如何基于多行多列动态创建postgresql数据透视表 - How to dynamically create a postgresql pivot table based on multiple rows and columns 如何按表格分组并创建新列以将原始值放在其中? - How to group by table and create the new columns to put the original value in there? Postgres在创建表中连接2列 - Postgres Concating a 2 columns in create table "在postgres的两列中获取字符串切片" - Get a string slices in two columns in postgres PostgreSQL使用来自不同表列的自动计算列创建表 - PostgreSQL create table with auto compute columns from different table columns Rails、Postgres:如何在不对列进行硬编码的情况下创建数据透视表并将其左连接到另一个表 - Rails, Postgres: How to CREATE a pivot table and LEFT JOIN it to another table without hardcoding the columns
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM