GORM: How to query has many relation?

Viewed 55

I need to find all students that belong to a school with a certain name.

type School struct {
    gorm.Model
    Students []Student
}

type Student struct {
    gorm.Model
    name string
    SchoolID uint 
}

I try this per the docs but it doesn't give me anything:

Database.Preload("Students", "name = ?", name).Find(&schools)

How can I achieve this with gorm?

1 Answers

Preload method takes a function as second argument. Here is an example:

database.Model(&School{}).Preload("Students", func(db *gorm.DB) *gorm.DB {
    return db.Where("studens.name = ?", name)
}).Find(&schools)
Related