'Is a Select() done against a key in the table's struct?

I have a database where one of the tables is managed through

type Token struct {
    gorm.Model
    Value  string
    User   User
    UserID uint
}

At some point, I am trying to retrieve all the elements in that table, but limited to only one field (Users). When doing the query without the Select(), I get everything as expected:

var tokens []Token
db.
    Preload("User").
    // Select("User").
    Find(&tokens)

An extract from the output:

(...)
{
    "ID": 27,
    "CreatedAt": "2022-03-11T20:24:01.0505503+01:00",
    "UpdatedAt": "2022-03-11T20:24:01.0505503+01:00",
    "DeletedAt": null,
    "Value": "admintoken",
    "User": {
        "ID": 27,
        "CreatedAt": "2022-03-11T20:24:01.0521975+01:00",
        "UpdatedAt": "2022-03-11T20:24:01.0521975+01:00",
        "DeletedAt": null,
        "UserName": "admin",
        "UserType": {
            "ID": 0,
            "Name": "",
            "UserID": 0
        }
    }
}
(...)

Since I only want to get the "User" object, I tried

var tokens []Token
db.
    Preload("User").
    Select("User").
    Find(&tokens)

but now the output is empty.

What should the Select() be against?



Solution 1:[1]

To select all Users that have at least one token you could use the following query:

var users []User
db.Where("id IN (?)","SELECT DISTINCT(user_id) FROM tokens").Find(&users)

Solution 2:[2]

I don't think Preload is a good option since it would do 2 queries to retrieve the result, why do 2 queries if you can retrieve expected result in only 1 query

To retrieve users who has token code can be updated as below:

var users []User
db.Table("users").Select("users.id, users.name").Joins("inner join tokens on tokens.user_id = users.id").Find(&users)
rows, err := db.Table("users").Select("users.id, users.name").Joins("inner join tokens on tokens.user_id = users.id").Rows()
for rows.Next() {
  ...
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Anni
Solution 2