Documentation ¶
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AddDeepFilters ¶
AddDeepFilters / addDeepFilter godoc
Gorm supports the following filtering:
type Person struct { Name string } map[string]any{ "name": "Jake" }
Which will return a list of people that are named 'Jake'. This is great for simple filtering but for more nested versions like the following it becomes problematic.
type Group struct { IDs int Name string } type Person struct { Name string Group Group GroupRef int }
// Get all the users belonging to 'some group'
map[string]any{ "group": map[string]any{ "name": "some group", }, }
Gorm does not understand that we expected to filter users based on their group, it's not capable of doing that automatically. For this we need to use subqueries. Find more info here: https://gorm.io/docs/advanced_query.html
This function is constructed to automatically convert those nested maps ("group": map[string]...) into subqueries. In order to do this, it takes the following steps:
- Get all the struct-type fields from the incoming 'object', ignore all simple types and interfaces
- Loop through all the key/values in the incoming map
- Add all the simple types to a simpleMap, GORM can handle these, For all the special (nested) structs, add a subquery that uses WHERE on the subquery.
- Add the simple filters to the query and return it.
Example ¶
Get all ObjectAs that are connected to ObhectB with Id 50
type ObjectB struct { ID int } type ObjectA struct { ID int ObjectB *ObjectB `gorm:"foreignKey:ObjectBID"` ObjectBID int } db, _ := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{}) _ = db.Use(New()) db.Create(&ObjectA{ ID: 1, ObjectB: &ObjectB{ ID: 50, }, }) filters := map[string]any{ "object_b": map[string]any{ "id": 50, }, } var result ObjectA db.Where(filters).Find(&result) fmt.Println(result)
Output: