dsfs504545 2018-03-30 05:25
浏览 788
已采纳

如何使用gorm获取多个用户的数据?

Database: MySql I have a two structs as follows:

type Person struct {
    gorm.Model
    Name    string
    Address string
}

type Address struct {
    gorm.Model
    PersonID int
    Address  []Address
}

I want to fetch data of multiple persons with there adresses. I tried it like:

var result []Person
db.Table("persons").Select("persons.id,persons.created_at, persons.updated_at,persons.deleted_at,persons.name,addresses.address").Joins("inner join addresses on addresses.person_id = persons.id").Scan(&result)

I got result:

[
  {
    ID: 13,
    CreatedAt: '2018-03-28T16:25:43+05:30',
    UpdatedAt: '2018-03-28T16:28:31+05:30',
    DeletedAt: null,
    Name: 'roshan',
    Address: null
  },
  {
    ID: 13,
    CreatedAt: '2018-03-28T16:25:43+05:30',
    UpdatedAt: '2018-03-28T16:28:31+05:30',
    DeletedAt: null,
    Name: 'roshan',
    Address: null
  },
  {
    ID: 14,
    CreatedAt: '2018-03-28T16:25:43+05:30',
    UpdatedAt: '0001-01-01T00:00:00Z',
    DeletedAt: null,
    Name: 'kunal2',
    Address: null
  }
];

expexted result is

[
  {
    ID: 13,
    CreatedAt: '2018-03-28T16:25:43+05:30',
    UpdatedAt: '2018-03-28T16:28:31+05:30',
    DeletedAt: null,
    Name: 'roshan',
    Address: ['pune', 'nagpur']
  },
  {
    ID: 14,
    CreatedAt: '2018-03-28T16:25:43+05:30',
    UpdatedAt: '0001-01-01T00:00:00Z',
    DeletedAt: null,
    Name: 'kunal2',
    Address: ['New York']
  }
];
  • 写回答

1条回答 默认 最新

  • dsgfdgh14569 2018-03-30 09:42
    关注

    First of all you probably should change your model declarations to this

    type Person struct {
        gorm.Model
        Name    string
        Address []Address
    }
    
    type Address struct {
        gorm.Model
        PersonID int
    }
    

    And then to preload associations you can use this query

    var person []Person
    
    err := db.Preload("Address").Find(&person).Error
    

    where you person param will be te results from db with preloaded addresses

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 keil 5 编程智能家具,风扇台灯开关,人体感应等
  • ¥100 找一名渗透方面的专家
  • ¥20 使用Matlab gui设计一个插补小程序
  • ¥15 evo评估时曲线出现问题
  • ¥15 eNSP拓扑图配置实验
  • ¥20 有没有兄弟会替换fmod studio的.bank文件内的音效?
  • ¥20 如何解决访问网址被屏蔽的情况
  • ¥15 本地运行的vue2项目,使用内网穿透,前端界面一直转圈圈
  • ¥20 powerbuilder datawindow控件导出Excel数据,可不可以不自动覆盖原数据,而是在后面新插入入数据。
  • ¥15 telegram 问题