Lessons Learned: GoLang GORM – filtering associations

The problem

Given the following code:

type User struct { 
   gorm.Model
   Username     string
   Orders       []Order
}

type Order struct {
   gorm.Model
   UserID      uint
   Foobar      string
}

The above Golang code defines a “Has Many” association, leading to a schema where a “User” “has many” “Orders”, with the “user_id” key acting as a foreign key.

How do we write GORM code to generate an SQL schema similar to the following:

SELECT * FROM orders WHERE user_id = "123" AND foobar = "abc"

i.e. get all the orders for the user “123” whose foobar field is “abc”

Solution

Looking at the GORM associations documentation, all the orders for a particular user can be found like so:

db.Model(&user).Related(&orders)

which allows us to filter by user id if we declare user to be something similar to:

user := User{
   id: 123,
}

However, at this point we’d end up with all the orders for the user in the variable “orders”. We next need to filter them, which can be done with the following:

db.Model(&user).Related(&orders).Where("foobar = ?", "abc")

This introduces the necessary filter, however GORM won’t execute that until a “Find” or “First” is also issued, which means our complete statement should be as follows:

db.Model(&user).Related(&orders).Where("foobar = ?", abc).Find(&orders)

The above statement will give us the filtered results stored within the orders variable

Advertisements