gorm icon indicating copy to clipboard operation
gorm copied to clipboard

Using a slice of structs in a WHERE clause

Open jessdwitch opened this issue 1 year ago • 1 comments

Your Question

I'm unsure if this is a bug/feature request/I'm just using it wrong, so starting with a question. This use case isn't explicitly covered in the docs. When I do something like this:

type Role struct {
  ID          int64
  Description string
}

roles := []*Role{
  {
    Description: "user",
  },
  {
    Description: "admin",
  },
  {
    Description: "qa",
  },
}

fmt.Println("LEN:", len(roles))
fmt.Println("ERR:", db.Where(&roles, "description").Find(&roles).Error)
fmt.Println("LEN:", len(roles))

for i, r := range roles {
  fmt.Printf("%d\t%+v", i, *r)
}

The print is something like:

LEN: 3
ERR: <nil>
LEN: 1
0    {ID: 9, Description: "qa"}

This does not return an error, but my slice (roles) is truncated down to len=1 and only includes the last value ("qa" in this case). I notice the docs don't mention this use case, so maybe this isn't possible, but the fact that I can use a slice model in other situations and this doesn't return an error makes me think maybe I'm just doing something wrong?

The document you expected this should be explained

https://gorm.io/docs/query.html#Struct-amp-Map-Conditions

Expected answer

I'd like to know if the truncation is intended behavior, and I guess if not, convert this to a bug report. If it is, what I should do as an alternative? Most straightforward I can think is to pull out the descriptions into a string slice and request that, but that's significantly uglier.

jessdwitch avatar May 18 '23 18:05 jessdwitch