gorm选择并以切片形式返回一列数据。

huangapple go评论112阅读模式
英文:

gorm select and returns a column in the form of a slice

问题

gorm有没有像PHP中的某个方法可以做到这样的事情?

  1. $name := db.Column("name")
  2. // $name的输出: ["joe", "john", .....]
  3. fmt.Println($name)

我想要做的是(伪代码):

  1. var ct []string
  2. db.Model("user").Column(&ct)
  3. // ct的输出: []string{"joe", "john", .....}
  4. fmt.Println(ct)

或者我必须使用结构体获取结果,然后格式化为切片吗?

gorm版本:v1.21.11

英文:

Is there gorm has the method to do this like something in PHP ?

  1. $name = $db->column("name");
  2. // output of $name: ["joe", "john", .....]
  3. print_r($name);

What I want to do (fake code):

  1. var ct []string
  2. db.Model("user").Column(&ct)
  3. // output of ct: []string{"joe", "john", .....}
  4. fmt.println(ct)

Or I must get result with strcut and then format to slice?

gorm version: v1.21.11

答案1

得分: 4

创建一个具有你想要获取的字段的类型,并声明一个具有该新创建类型的数组。

  1. type name string
  2. var arr []name
  3. // 使用表格
  4. err := db.Table("your table name").Select("name").Find(&arr).Error
  5. // 使用模型字段
  6. err := db.Model(User{}).Select("name").Find(&arr).Error

你可以查看 gorm 的官方文档:
https://gorm.io/docs/advanced_query.html#Smart-Select-Fields

英文:

Create a type with the field you want to grab and and declare an array with that newly created type.

  1. type name string
  2. var arr []name
  3. // with table
  4. err := db.Table("your table name").Select("name").Find(&arr).Error
  5. // with model field
  6. err := db.Model(User{}).Select("name").Find(&arr).Error

You can look into the gorm's official documentation:
https://gorm.io/docs/advanced_query.html#Smart-Select-Fields

huangapple
  • 本文由 发表于 2021年8月30日 16:14:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/68980863.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定