【问题标题】:how query to ManyToMany field in gorm如何查询gorm中的ManyToMany字段
【发布时间】:2021-04-07 02:06:40
【问题描述】:

我正在使用 gorm 处理数据库查询,我有 2 个模型 (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
}

我使用此查询接收我的用户列表:


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

这可行,但显示公司为 Null

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

我应该在查询中使用什么来在列表中显示用户公司 (id)?

【问题讨论】:

    标签: go go-gorm go-gin


    【解决方案1】:

    您必须使用带有自定义加载的 Preload 方法才能将公司 ID 加载到 Companies 字段中。

    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
    }
    

    您可以在this 链接或this 问题上找到更多详细信息。

    【讨论】:

    • 是的,我用过这个,但这会返回公司的所有信息...我只想显示公司 id
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-01
    • 2018-11-25
    • 2014-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多