Lessons Learned: GoLang GORM – filtering associations

The problem

Given the following code:

type User struct { 
   Username     string
   Orders       []Order

type Order struct {
   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”


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


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).Where("foobar = ?", "abc").Related(&orders)

This introduces the necessary filter, and as @zorieq pointed out to me, the “Related()” method does execute the query. As a bonus, you can add “.Debug()” to preview queries

Update 8/10/2019: included updates from @zorieq’s tweet: