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

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?

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.