2

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 Answer 1

1

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.