Home > Software engineering >  how to use RowsAffected in gorm golang
how to use RowsAffected in gorm golang

Time:12-22

i created a function in repository however I get an error on RowsAffected

func (r *repositoryUser) EntityResultAllTotal(search string) (*models.ModelUser, error) {
    cari := "%"   search   "%"
    var users []models.ModelUser
    result := r.db.Where("username = ?", cari).Find(&users).Error
    return result.RowsAffected
        // result.RowsAffected undefined (type error has no field or method RowsAffected)
}

how to solve ?

CodePudding user response:

To get the RowsAffected value you've to use .RowsAffected instead of .Error after the Find method. I rewrote your code as follows:

func (r *repositoryUser) EntityResultAllTotal(search string) (*models.ModelUser, error) {
    cari := "%"   search   "%"
    var users []models.ModelUser
    rowsAffected := r.db.Where("username = ?", cari).Find(&users).RowsAffected
    return rowsAffected
}

Let me know if it works, thanks!

CodePudding user response:

You can use the following way:

func (r *repositoryUser) EntityResultAllTotal(search string) (*models.ModelUser, error) {
    var(
      users []models.ModelUser
      cari = fmt.Sprintf("%%%s%%", search)
    )
    result := r.db.Where("username = ?", cari).Find(&users)
    if result.Error != nil {
        return users, result.Error
    }

    fmt.Println(result.RowsAffected) // returns int64
    return users, nil
}
  • Related