I'm trying to query a many-to-many relationship using the Gorm ORM for Go.
I have two structs: User
& Address
.
type User struct {
// gorm.Model
UUID string `gorm:"type:uuid;primary_key;auto_increment:false"`
Firstname string
// ...
Addresses []Address `gorm:"many2many:useraddresses"`
}
// Address represents the Postgres SQL address model
type Address struct {
UUID string `gorm:"type:uuid;primary_key;auto_increment:false"`
Line1 string
// ...
}
I took inspiration from the many-to-many example shown here in the documentation, (except I used a slice of users []User
instead of a single user).
var u []User
var a []Address
If I query just using the users as a Model, all users are returned (sends sql query SELECT * FROM "users"
):
db.Model(&u).Find(&u)
However, if I include related Addresses, surgeons are returned, but no Addresses:
db.Model(&u).Related(&a, "Addresses").Find(&u)
This creates another sql query that precedes the first:
SELECT "addresses".*
FROM "addresses" INNER JOIN "useraddresses" ON "useraddresses"."address_uuid" = "addresses"."uuid"
WHERE (1 <> 1)
Of course, the where false
condition prevents any addresses from being returned.
Can anyone shed light on how I can include the addresses using the db.Model
method of Gorm?