英文:
How to implement preloading in gorm
问题
我正在使用gorm。
我遇到了以下问题,希望有人能帮助我解决或更详细地解释一下:
type User struct {
ID int
Name string
Addresses []Address
}
type Address struct {
UserID int `gorm:"index;not null"`
Address string
City string
Zipcode int
Country string
}
if err := db.Select("name").Preload("Addresses").Find(&users).Error; err != nil {
// 显示错误消息
} else {
//
}
结果:
[
{
"created_at": "2017-04-02T00:07:59Z",
"updated_at": "2017-04-02T00:07:59Z",
"name": "Richard"
}
]
SQL 日志:
SELECT * FROM `users` WHERE `users`.deleted_at IS NULL AND ((1 <> 1))
期望结果:
[
{
"created_at": "2017-04-02T00:07:59Z",
"updated_at": "2017-04-02T00:07:59Z",
"name": "Richard",
"addresses": [
{
"address": "No 1, Street 5",
"city": "New York",
"country": "US"
}
]
}
]
我已经在StackOverflow上研究了一些其他帖子,但没有看到任何解决方案。
英文:
I'm using gorm.
I have an issue bellow, hope somebody can help me resolve or explain more about that
type User struct {
ID int
Name string
Addresses []Address
}
type Address struct {
UserID int `gorm:"index;not null"`
Address string
City string
Zipcode int
Country string
}
if err := db.Select("name").Preload("Addresses").Find(&users).Error; err != nil {
// Display error message
} else {
//
}
Result:
[
{
"created_at": "2017-04-02T00:07:59Z",
"updated_at": "2017-04-02T00:07:59Z",
"name": "Richard"
}
]
SQL log:
SELECT * FROM `users` WHERE `users`.deleted_at IS NULL AND ((1 <> 1))
Expect result:
[
{
"created_at": "2017-04-02T00:07:59Z",
"updated_at": "2017-04-02T00:07:59Z",
"name": "Richard",
"addresses": [
{
"address": "No 1, Street 5",
"city": "New York",
"country": "US"
}
]
}
]
I have researched some other post on StackOverflow but don't see any solutions
答案1
得分: 4
选择缺失的id
字段,以便不应用预加载。下面的代码将解决这个问题。
if err := db.Select("id, name").Preload("Addresses").Find(&users).Error; err != nil {
// 显示错误消息
} else {
//
}
英文:
Select missing id
fields so preloading was not applied. Bellow code will be resolve issue
if err := db.Select("id, name").Preload("Addresses").Find(&users).Error; err != nil {
// Display error message
} else {
//
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论