Bens
Bens

Reputation: 946

How to exclude a column from being Selected

I am using Go as language code and gorm as ORM

This is the struct model:

type Product struct {
   ID        int     `gorm:"primaryKey" json:"id"`
   Name      string  `gorm:"notNull;size:125" json:"name"`
   Inventory int     `gorm:"-:migration" json:"inventory"`
}

when I perform Join like this:

DB.Joins("Product")

the inventory field is present in select statement cause an error something like:

Unknown column 'Product.inventory' in 'field list'

of course it doesn't exist in products table because of this tag "-:migration"

what tag should I use to make Inventory being ignored/exclude in select statement???

I only want to exclude inventory from select statement, I want the field still there when parsed to json

Upvotes: 3

Views: 781

Answers (1)

ossan
ossan

Reputation: 1855

The tag that you should use is gorm:"-:all" that also involves read/write permission other than the migration one.
You can read more about this in the official doc: https://gorm.io/docs/models.html#Fields-Tags
I'll share with you the code I wrote to test this out:

package main

import (
    "fmt"

    "gorm.io/driver/postgres"
    "gorm.io/gorm"
)

type Product struct {
    ID        int    `gorm:"primaryKey" json:"id"`
    Name      string `gorm:"notNull;size:125" json:"name"`
    Inventory int    `gorm:"-:all" json:"inventory"`
}

func main() {
    dsn := "host=localhost user=postgres password=postgres dbname=postgres port=5432 sslmode=disable"
    db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
    if err != nil {
        panic(err)
    }

    db.AutoMigrate(&Product{})

    db.Create(&Product{Name: "pen"})
    db.Create(&Product{Name: "box"})

    var product Product
    db.Find(&product, 1)

    // here you can still access and set the JSON. 
    // Obviously, the value cannot be retrieved from the DB as it doesn't exist there
    product.Inventory = 22 

    data, _ := json.Marshal(product)

    fmt.Println(string(data))
}

Let me know if this helps, thanks!

Upvotes: 1

Related Questions