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

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

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

问题

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

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

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

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

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

gorm版本:v1.21.11

英文:

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

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

What I want to do (fake code):

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

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

gorm version: v1.21.11

答案1

得分: 4

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

type name string
var arr []name

// 使用表格
err := db.Table("your table name").Select("name").Find(&arr).Error

// 使用模型字段
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.

type name string
var arr []name

// with table
err := db.Table("your table name").Select("name").Find(&arr).Error

// with model field
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:

确定