如何在GORM中仅根据其祖父表的键选择子表(该键仅存在于其直接父表中)

huangapple go评论86阅读模式
英文:

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"的信息 如何在GORM中仅根据其祖父表的键选择子表(该键仅存在于其直接父表中)

请帮帮我,谢谢!

英文:

如何在GORM中仅根据其祖父表的键选择子表(该键仅存在于其直接父表中)

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 如何在GORM中仅根据其祖父表的键选择子表(该键仅存在于其直接父表中)

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

huangapple
  • 本文由 发表于 2022年10月8日 19:18:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/73996556.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定