erfanmorsali
erfanmorsali

Reputation: 165

how query to ManyToMany field in gorm

I'm using gorm to handle database queries and I have 2 models (ManyToMany) :

type Person struct {
    ID        uint      `json:"id" gorm:"primary_key;unique;autoIncrement"`
    Name      string    `json:"name" binding:"required"`
    Family    string    `json:"family" binding:"required"`
    Companies []Company `json:"companies" gorm:"many2many:person_companies;"`
}


type Company struct {
    ID   uint   `json:"id" gorm:"primary_key;unique;autoIncrement"`
    Name string `json:"name"`
    cars []Car
}

i use this query for receive list of my users:


func GetAllPeople() *[]domain.Person {
    var people []domain.Person
    db.Find(&people)
    return &people
}

this works but shows me Null for companies

{
      "id": 0,
      "name": "erfan",
      "family": "",
      "companies": null
}

what should I use in query to show users companies (id) in a list?

Upvotes: 0

Views: 369

Answers (1)

Emin Laletovic
Emin Laletovic

Reputation: 4324

You will have to use the Preload method with custom loading to just load the company ID's into the Companies field.

func GetAllPeople() *[]domain.Person {
    var people []domain.Person
    tx := db.Preload("Companies", func(db *gorm.DB) *gorm.DB {
       return db.Select("ID")
    }).Find(&people)
    if tx.Error != nil {
      // handle error
    }
    return &people
}

You can find more details on this link or this question.

Upvotes: 2

Related Questions