登录
首页 >  Golang >  Go问答

如何查询gorm中的ManyToMany字段

来源:stackoverflow

时间:2024-04-13 09:39:33 449浏览 收藏

各位小伙伴们,大家好呀!看看今天我又给各位带来了什么文章?本文标题《如何查询gorm中的ManyToMany字段》,很明显是关于Golang的文章哈哈哈,其中内容主要会涉及到等等,如果能帮到你,觉得很不错的话,欢迎各位多多点评和分享!

问题内容

我使用 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)?


解决方案


您必须使用带有自定义加载的 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 问题找到更多详细信息。

好了,本文到此结束,带大家了解了《如何查询gorm中的ManyToMany字段》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>