【问题标题】:gorm select and returns a column in the form of a slicegorm 选择并以切片的形式返回一列
【发布时间】:2021-08-30 08:14:02
【问题描述】:

gorm 是否有类似 PHP 中的方法来执行此操作?

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

我想做什么(假代码):

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

或者我必须使用 strcut 得到结果,然后格式化为切片?

gorm 版本:v1.21.11

【问题讨论】:

    标签: go go-gorm


    【解决方案1】:

    使用您要抓取的字段创建一个类型,并使用该新创建的类型声明一个数组。

    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
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-29
      • 2019-01-28
      • 1970-01-01
      • 2018-02-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多