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.

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

报告相同问题?

悬赏问题

  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源