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

时间:2018-03-30 05:25:53

标签: mysql go go-gorm

数据库:MySql 我有两个结构如下:

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

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

我想在那里获取多个人的数据。 我尝试过这样:

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)

我得到了结果:

[
  {
    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
  }
];

被驱逐的结果是

[
  {
    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 个答案:

答案 0 :(得分:1)

首先,您可能应该将模型声明更改为此

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

type Address struct {
    gorm.Model
    PersonID int
}

然后预加载关联,您可以使用此查询

var person []Person

err := db.Preload("Address").Find(&person).Error

你的人员参数将是来自带有预加载地址的数据库的结果