英文:
GORM: How to query has many relation?
问题
我需要找到属于特定名称的学校的所有学生。
type School struct {
gorm.Model
Students []Student
}
type Student struct {
gorm.Model
name string
SchoolID uint
}
我按照文档尝试了以下方法,但没有返回任何结果:
Database.Preload("Students", "name = ?", name).Find(&schools)
我该如何使用gorm实现这个功能?
英文:
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
得分: 1
Preload方法接受一个函数作为第二个参数。以下是一个示例:
database.Model(&School{}).Preload("Students", func(db *gorm.DB) *gorm.DB {
return db.Where("students.name = ?", name)
}).Find(&schools)
英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论