Pain Point Description

As described in the previous chapters, if a given array is uninitialized (with a value of nil), the ORM will not automatically initialize that array when no data is queried based on the given conditions. Thus, if this uninitialized array result is encoded via JSON, it will be converted to a null value.

  1. package main
  2. import (
  3. _ "github.com/gogf/gf/contrib/drivers/mysql/v2"
  4. "fmt"
  5. "github.com/gogf/gf/v2/encoding/gjson"
  6. "github.com/gogf/gf/v2/frame/g"
  7. "github.com/gogf/gf/v2/os/gtime"
  8. )
  9. func main() {
  10. type User struct {
  11. Id uint64 // Primary Key
  12. Passport string // Account
  13. Password string // Password
  14. NickName string // Nickname
  15. CreatedAt *gtime.Time // Creation Time
  16. UpdatedAt *gtime.Time // Update Time
  17. }
  18. type Response struct {
  19. Users []User
  20. }
  21. var res = &Response{}
  22. err := g.Model("user").WhereGT("id", 10).Scan(&res.Users)
  23. fmt.Println(err)
  24. fmt.Println(gjson.MustEncodeString(res))
  25. }

After execution, the terminal displays the result as:

  1. <nil>
  2. {"Users":null}

In most scenarios, the data queried by the ORM needs to be rendered on a browser page, which means the returned data needs to be processed by frontend JS. To make it more friendly for frontend JS to handle backend return data, when no data is queried on the backend, it is expected to return an empty array structure instead of a null attribute value.

Improvement Plan

In this scenario, you can provide an initialized empty array to the Scan method of the ORM. When the ORM doesn’t query any data, the array attribute remains an empty array, rather than nil, and the returned JSON encoding will not be a null value.

  1. package main
  2. import (
  3. _ "github.com/gogf/gf/contrib/drivers/mysql/v2"
  4. "fmt"
  5. "github.com/gogf/gf/v2/encoding/gjson"
  6. "github.com/gogf/gf/v2/frame/g"
  7. "github.com/gogf/gf/v2/os/gtime"
  8. )
  9. func main() {
  10. type User struct {
  11. Id uint64 // Primary Key
  12. Passport string // Account
  13. Password string // Password
  14. NickName string // Nickname
  15. CreatedAt *gtime.Time // Creation Time
  16. UpdatedAt *gtime.Time // Update Time
  17. }
  18. type Response struct {
  19. Users []User
  20. }
  21. var res = &Response{
  22. Users: make([]User, 0),
  23. }
  24. err := g.Model("user").WhereGT("id", 10).Scan(&res.Users)
  25. fmt.Println(err)
  26. fmt.Println(gjson.MustEncodeString(res))
  27. }

After execution, the terminal displays the result as:

  1. <nil>
  2. {"Users":[]}