GORM:如何查询一对多关系?

huangapple go评论76阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2022年6月25日 14:42:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/72751789.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定