如何使用gorm填充和嵌入阵列? [英] How to populate and embedded array with gorm?

查看:54
本文介绍了如何使用gorm填充和嵌入阵列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个结构,其数据如下:

I have 2 structs with data like this:

type User struct {
  Pics Pic[]
}

type Pic struct {
  Id int   
  UserId int64
}

尽管每次我插入一个用户,但每次我找到用户时,每张图片都会插入到他们的桌子上,图片不会被填充:

Although everytime I insert an User, Each of the pics are inserted on their table everytime I find the users, pics are not populated:

var users []User
db.Limit(pagesize).Where("updated_at > ?", date).Find(&users)

我做错什么了吗?

推荐答案

您的模型(结构)没有任何意义,因为 User 具有 Pic 数组表示'一对多'的用户与图片的关系,但是您的用户本身没有id属性,因此不能与 Pic 表中的项目相关.

Your models (the structs) don't really make sense because User have a Pic array indicates a 'one to many' user to pics relationship however your user has no id property itself and there for cannot be related to items on the Pic table.

用户应具有属性 Id ,它将是它的主键,而 UserId 是与之相关的Pic上的外键.如果没有这两个表/实体之间的关系",就无法通过查询用户来返回图片.

User should have a property Id which will be it's primary key and UserId is a foreign key on Pic that relates to it. Without the 'relation' between these two tables/entities there's no way you're going to return pics by querying users.

我不确定要使代码正常工作需要做些什么,因为示例不完整,但是首先需要的是 Id 属性,您应该将其指定为带有gorm的主键.注释.您还应该在Pic结构上添加注释,说明UserId是外键,而Id是主键.

I'm not sure what all you need to do to make your code work since the example is incomplete but the first thing you need is an Id property which you should designate as a Primarykey with gorm annotations. You also should have annotations on the Pic struct saying UserId is a foreign key and Id is it's primary key.

此外,仅是您的阵列未嵌入.嵌入是您不使用的语言功能,如果嵌入属性没有名称,则可以直接从嵌入类型的实例访问其属性.

Also, just fyi your array is not embedded. Embedding is a language feature which you're not using, if you embed the property it has no name and it's properties can be accessed directly from an instance of the embedding type.

这篇关于如何使用gorm填充和嵌入阵列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆