【问题标题】:How can I transform a subquery to join in gorm?如何转换子查询以加入 gorm?
【发布时间】:2022-01-09 12:11:34
【问题描述】:

我正在使用 GORM,我有这些模型:

type User struct {
  ID    uint
  UUID  uuid.UUID
  Email string
}

type Profile struct {
  ID     uint
  UUID   uuid.UUID
  Domain string
  UserID uuid.UUID
  User   User `gorm:"references:UUID"`
}

现在我想查找所有具有域的个人资料的用户,例如example.com.

我已经尝试了一些“加入”查询,但我没有让它工作。但是我设法通过使用子查询使其工作:

var users []users

DB.Where(
  "uuid IN (?)",
  DB.Select("user_id").Where("domain = ?", "example.com").Table("profiles")
).Find(&users)

但我不认为这是一种非常优雅的方式。我认为加入会更直接。如何将此子查询转换为联接查询?

谢谢!

【问题讨论】:

  • 我认为您在子查询中选择了错误的列 DB.Select("user_id") 应该是 DB.Select("uuid") 对吧? (gorm: "references:UUID")
  • @DavidYappeter 没有子查询工作正常。配置文件表上的字段称为user_id,它引用了用户的字段uuid

标签: mysql database go go-gorm


【解决方案1】:

如果您更喜欢使用 gorm 内置功能而不是原始查询连接,您可以试试这个:

profile := &Profile{Domain: "example.com"}
user := &User{}

db.Select("User.*").Joins("User").Model(&Profile{}).Where(profile).Find(&user)

如果我们像这样使用 gorm 调试模式:

db.Debug().Select("User.*").Joins("User").Model(&Profile{}).Where(profile).Find(&user)

SQL查询日志会是这样的:

SELECT User.*,`User`.`id` AS `User__id`,`User`.`uuid` AS `User__uuid`,`User`.`email` AS `User__email` FROM `profiles` LEFT JOIN `users` `User` ON `profiles`.`user_id` = `User`.`uuid` WHERE `profiles`.`domain` = 'example.com'

【讨论】:

    【解决方案2】:

    试试这个

    DB.Select("u.*").Table("users u").Joins("INNER JOIN profiles p on p.user_id = u.uuid").Where("p.domain = ?", "example.com").Find(&users)
    

    这将导致:

    SELECT u.* FROM users u INNER JOIN profiles p on p.user_id = u.uuid WHERE p.domain = "example.com"
    

    【讨论】:

      猜你喜欢
      • 2012-02-07
      • 1970-01-01
      • 1970-01-01
      • 2023-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多