Retrieving Sum of Salary Column using GORM
In your code, you attempt to retrieve the sum of the salary column from a Postgres table named "people" using GORM. However, your current approach has some limitations.
To correctly retrieve the sum of the salary column, it's recommended to use GORM's Scan function instead of manually constructing a SQL query. This approach allows you to define a struct that represents the result you want to retrieve.
Example:
<code class="go">func GetSalarySum(c echo.Context) error { db, err := gorm.Open("postgres", "host=localhost port=5433 user=postgres dbname=testone password=root sslmode=disable") checkError(err) defer db.Close() type SalarySum struct { Sum uint `gorm:"column:sum"` } var salarySum SalarySum if err := db.Table("people").Select("SUM(salary) AS sum").Scan(&salarySum).Error; err != nil { fmt.Println("error->", err) } return c.JSON(http.StatusOK, salarySum) }</code>
In this code:
This updated code should correctly retrieve and return the sum of the salary column from the "people" table.
The above is the detailed content of How to Retrieve the Sum of a Column Value Using GORM and Scan?. For more information, please follow other related articles on the PHP Chinese website!