dongpo1216 2019-06-25 04:18
浏览 15
已采纳

选择特定列时如何获取对应的字段?

Here is the code:

// User Model
type User struct {
    UserID        int           `db:"user_id"`
    UserNme       string        `db:"user_nme"`
    UserEmail     string        `db:"user_email"`
    UserAddressID sql.NullInt64 `db:"user_address_id"`
}
func (ur *userRepository) FindAll() ([]models.User, error) {
    var users []models.User
    query := "select user_nme from users"
    err := ur.Db.Select(&users, query)
    if err != nil {
        return nil, err
    }
    return users, nil
}

Result:

&[]models.User{models.User{UserID:0, UserNme:"Jay Durgan", UserEmail:"", UserAddressID:sql.NullInt64{Int64:0, Valid:false}}, models.User{UserID:0, UserNme:"Arne Balistreri", UserEmail:"", UserAddressID:sql.NullInt64{Int64:0, Valid:false}}, models.User{UserID:0, UserNme:"Greg Willms", UserEmail:"", UserAddressID:sql.NullInt64{Int64:0, Valid:false}}, models.User{UserID:0, UserNme:"Lady Aisha McLaughlin", UserEmail:"", UserAddressID:sql.NullInt64{Int64:0, Valid:false}}, models.User{UserID:0, UserNme:"Mrs. Phoebe Boyle", UserEmail:"", UserAddressID:sql.NullInt64{Int64:0, Valid:false}}}% 

As you can see, I didn't query user_id, user_email and user_address_id columns, but the result give me these fields with zero value.

So, is there a way only get the fields correspond to the queried columns? Beside, I don't want to write it like this: &user.userNme, &user.xxx, &user.xxx which means write each field and populate it. It's too verbose.

Expected result is: {UserNme: "Jay Durgan"}...

  • 写回答

2条回答 默认 最新

  • donglong1465 2019-06-25 06:35
    关注

    By using struct, you can't.

    The other fields will still be there with it's zero value. The fields are property of the struct so whether you need it or not, whether it stored retrieved value from db operation or not, all the fields will still be there.

    The only solution for your case is by using map, so only value of correspondent fields will be retrieved.

    var users []map[string]interface{}
    query := "select user_nme from users"
    err := ur.Db.Select(&users, query)
    if err != nil {
        return nil, err
    }
    

    Result:

    &[]map[string]interface{}{map[string]interface{}{UserNme:"Jay Durgan"}, ...}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改