gorm icon indicating copy to clipboard operation
gorm copied to clipboard

How to Select ignored field gorm:"-" ?

Open Fakerr opened this issue 2 years ago • 6 comments

Your Question

In Gorm v1, Selecting an ignored field used to work:

type user struct {
    ID     int64,
    Name   string,
    Amount  float64 `gorm:"-"`  // Amount column doesn't exist in users table.
}

var user models.User
s.db.Select(`users.*, SUM(values.amount) as amount`).
       Joins("join values on values.user_id = users.id").
       Where("users.id = ?", userID).
       First(&user)

But it's not the case anymore in Gorm V2 (No error, but the user.Amount value will be equal to 0).

How can I achieve the same thing in V2 ?

I do not want to set the permission for the Amount field to read Amount float64 `gorm:"->" because I have other endpoints that do a simple fetch like this:

var user models.User
db.Where("id = ?", userID).First(&user)

and changing the permission to read, will throw me this error: ERROR: column users.amount does not exist

Fakerr avatar Apr 21 '22 15:04 Fakerr

You need to read the field amount in the first case but not in the second case, and there's no way to do that with field permissions.

You can use other struct like this

type UserExt struct {
	User
	Amount float64
}

...

var userExt models.UserExt
s.db.Select(`users.*, SUM(values.amount) as amount`).
       Joins("join values on values.user_id = users.id").
       Where("users.id = ?", userID).
       First(&userExt)

a631807682 avatar Apr 24 '22 07:04 a631807682

The problem is that the field doesn't exist in the database. It's a custom one that we calculate during Select (in the example above, it's the SUM of another column in another table).

This used to work fine in v1 and it was such a helpful feature, I don't know why it changed in V2.

The proposed solutions to use a wrapper struct (like above) or to make the field read only gorm:"->" and Omit the column when it's needed are not very good solutions for our use case. It should remain simple as it used to be. @jinzhu thoughts on this ?

Fakerr avatar May 13 '22 04:05 Fakerr

This issue has been automatically marked as stale because it has been open 360 days with no activity. Remove stale label or comment or this will be closed in 180 days

github-actions[bot] avatar May 09 '23 02:05 github-actions[bot]

I have the same case. Commenting to re-open the issue and hopefully get some resolution 🤞

viktorstaikov avatar Oct 02 '23 21:10 viktorstaikov

+1. Same problem. Nobody found a solution?

reantg avatar Apr 11 '24 12:04 reantg