首页 文章

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

提问于
浏览
0

我正在使用带有MySQL驱动程序的Go的gorm,这就是我正在尝试做的事情 . 这是我的两个结构:

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
}

从代码中可以看出,struct User 应该与Sessions有很多关系 .

现在让's suppose I have a user record in the database, and a session record in the sessions table with the user'的ID . 我希望能够根据会话ID检索用户数据 . 也就是说,找到基于 SessionID 的会话记录,然后根据该会话的 UserID 获取用户信息 .

在纯MySQL中,我会这样做:

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

或者我可以通过这样的连接来做到这一点

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`

无论如何,如果不采用原始SQL,我将如何使用gorm?

1 回答

相关问题