假设有两个表:'users' 和 'posts',一个用户可以有多篇文章,他们之间的关系是 'users' 表的 'id' 字段和 'posts' 表的 'user_id' 字段关联。

下面是一个使用 'joins' 和 'preload' 联合查询的例子:

type User struct {
    ID    int
    Name  string
    Posts []Post 'gorm:"foreignKey:UserID"'
}

type Post struct {
    ID     int
    UserID int
    Title  string
    Body   string
}

func GetUserWithPosts(db *gorm.DB, userID int) (*User, error) {
    var user User
    err := db.Model(&User{}).
        Joins("left join posts on users.id = posts.user_id").
        Where("users.id = ?", userID).
        Preload("Posts").
        First(&user).Error
    if err != nil {
        return nil, err
    }
    return &user, nil
}

在这个例子中,我们使用 'Joins' 方法指定了 'users' 和 'posts' 表的关联条件,使用 'Preload' 方法指定了需要预加载的关联表 'Posts'。

在 'User' 结构体中,我们使用 'foreignKey' 标签指定了 'Posts' 字段和 'Post' 结构体的外键关联关系。这样在预加载时,GORM 就知道如何根据 'users' 表的 'id' 字段和 'posts' 表的 'user_id' 字段进行关联。

在查询完成后,'User' 结构体的 'Posts' 字段会自动填充为该用户的所有文章。

GORM Preload 和 Joins 联合使用:指定关联表查询

原文地址: https://www.cveoy.top/t/topic/mQxh 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录