Reputation: 1175
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
Upvotes: 2
Views: 10718
Reputation: 764
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
Upvotes: 6