douchen7324 2017-12-05 06:41
浏览 10
已采纳

结构用户-有很多会话。 查找给定会话的用户

I'm using gorm for Go with MySQL driver, and here's what I'm trying to do. Here are my two structs:

type User struct {
    ID       uint      `gorm:"primary_key"`
    Email    string    `sql:"unique_index;not null;type:varchar(64)"`
    Password string    `sql:"index;not null;type:varchar(64)"`
    Sessions []Session `gorm:"ForeignKey:UserID"`
    Roles    []Role    `gorm:"many2many:users_roles;"`
    Level    uint      `sql:"not null;type:tinyint(1);DEFAULT:1"`
}

type Session struct {
    ID       uint      `gorm:"primary_key"`
    SessionID string `sql:"index"`
    UserID    uint   `sql:"index"`
    UpdatedAt time.Time
}

As is seen from the code, a struct User is supposed to have a has many relationship with the Sessions.

Now let's suppose I have a user record in the database, and a session record in the sessions table with the user's ID. I'd like to be able to retrieve the user data based on the Session ID. That is, find a session record based on SessionID, and then grab the user info based on the UserID of that session.

In pure MySQL, I'd do it like this:

SELECT
    *
FROM
    `users
WHERE `id` = (SELECT `user_id` FROM `sessions` WHERE `session_id` = <MY-SESSION-ID> LIMIT 1)

Or I could do it with a join like this

SELECT
    `u`.*
FROM
    `users` `u`
LEFT JOIN `sessions` `s`
ON `s`.`user_id` = `u`.`id`
WHERE
    `s`.`session_id` = <MY-SESSION-ID>
GROUP BY `u`.`id`

Anyway, how would I do it with gorm without resorting to raw SQL?

  • 写回答

1条回答 默认 最新

  • dqhdz04240 2017-12-05 06:57
    关注

    What you want is gorm's preloading feature: http://jinzhu.me/gorm/crud.html#preloading-eager-loading

    It has the ability to filter the child table with a where-like syntax.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)