可以。在 GORM v1 中,可以使用 db.Table() 方法来定义要使用的表,然后在 Related() 方法中指定关联的模型。例如:

type User struct {
    ID       int
    Name     string
    Articles []Article `gorm:"ForeignKey:AuthorID"`
}

type Article struct {
    ID        int
    Title     string
    Body      string
    AuthorID  int
    Author    User `gorm:"ForeignKey:AuthorID"`
}

// 查询 ID 为 1 的 User 的所有 Article
var user User
db.Table("users").Where("id = ?", 1).Related(&user.Articles)

在上面的示例中,我们使用 db.Table("users") 来指定要查询的表为 users。然后,在 Related() 方法中,我们将 &user.Articles 传递给它,以便将查询结果映射到 User 结构体的 Articles 字段中。

gorm v1 中related 可以和dbtable联合使用吗

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

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