Home > OS >  How to only select the child table depending on its grandparent table's key in GORM (this key o
How to only select the child table depending on its grandparent table's key in GORM (this key o

Time:10-09

enter image description here

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 !

CodePudding user response:

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
  •  Tags:  
  • go
  • Related