英文:
How to only select the child table depending on its grandparent table's key in GORM (this key only exists in its direct Parent table)
问题
我在这个图片中看到了3个表格。
一个名为"user"的表格可以有多个"catalog_habit",而"catalog_habit"可以有多个"habit"。
我正在尝试使用Gorm Preload的方法,通过使用"user"表格的特定"id"主键,使API能够显示与"habit"相关的所有表格。
它可以显示3个表格的所有信息,但我只想为前端开发人员获取"Habit"的信息
请帮帮我,谢谢!
英文:
I have 3 tables in this image.
A table "user" can have many "catalog_habit", and the "catalog_habit" can have many "habit".
I'm trying to find a way of using Gorm Preload to make API to display all of "habit"-relevant tables from a particular "id" primary key of "User" table.
It can display every information of 3 tables, but I want to get the "Habit" info only for Frontend guys
Please help me out, thanks !
答案1
得分: 0
这取决于你想要如何加载和显示这些数据。
只加载指定用户的所有习惯
var habits []Habit
err := db.Joins("JOIN catalog_habit ch ON ch.id = habit.catalog_id").
Joins("JOIN user u ON u.id = ch.user_id").
Where("u.id = ?", userID).Find(&habits).Error
加载用户及其目录习惯和习惯
为此,你的结构体应该类似于以下内容:
type User struct {
//其他字段
CatalogHabits []CatalogHabit
}
type CatalogHabit struct {
//其他字段
UserID int64
Habits []Habit
}
type Habit struct {
//其他字段
CatalogHabitID int64
}
然后,你可以编写一个查询来加载用户数据以及他的目录习惯和习惯:
var user User
err := db.Preload("CatalogHabits.Habits").First(&user, userID).Error
英文:
It depends on how you want to load and display this data.
Just load all habits for the specified user
var habits []Habit
err := db.Joins("JOIN catalog_habit ch ON ch.id = habit.catalog_id").
Joins("JOIN user u ON u.id = ch.user_id").
Where("u.id = ?", userID).Find(&habits).Error
Load the user and its catalog habits and habits
For this, your structs should be something like this:
type User struct {
//other fields
CatalogHabits []CatalogHabit
}
type CatalogHabit struct {
// other fields
UserID int64
Habits []Habit
}
type Habit struct {
//other fields
CatalogHabitID int64
}
Then, you can write a query to load the user data, along with his catalog habits and habits:
var user User
err := db.Preload("CatalogHabits.Habits").First(&user, userID).Error
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论