How GORM reads the value of the alias field

Viewed 1323

When querying data, an alias is set for a field. How do I use GORM to read the value of the alias field into the structure?

Table Structure

DROP TABLE IF EXISTS "test"."test";
CREATE TABLE "test"."test" (
  "id" varchar(32) NOT NULL,
  "name" varchar(255) COLLATE "pg_catalog"."default",
  "remark" varchar(255) COLLATE "pg_catalog"."default"
);
ALTER TABLE "test"."test" ADD CONSTRAINT "test_pkey" PRIMARY KEY ("id");

Table corresponding model structure

type Test struct {
    ID     string `gorm:"column:id;type:varchar(32);primaryKey;comment:Unique ID" json:"id"`
    Name   string `gorm:"column:name;type:varchar(255);comment:Name Info" json:"name"`
    Remark string `gorm:"column:remark;type:varchar(255);comment:Remark Info" json:"remark"`

    MoreInfo string `gorm:"-" json:"moreInfo"` // Non-table field

}

GORM query

gormDB is the initialized gorm database connection.

test := Test{ID: "0000000001"}
gormDB.Select("*, 'testMoreInfoVal' AS more_Info").Where(&test).Find(&test)

Q: How to use GORM to read the alias field more_Info that does not exist in the table into the MoreInfo property of the Test structure?

1 Answers

If the table structure is set and you aren't using AutoMigrate then this is solved by just changing your tags to make MoreInfo a read-only field and making sure you use the alias more_info to match the way Gorm does DB -> Go naming translation.

type Test struct {
    ID     string `gorm:"column:id;type:varchar(32);primaryKey;comment:Unique ID" json:"id"`
    Name   string `gorm:"column:name;type:varchar(255);comment:Name Info" json:"name"`
    Remark string `gorm:"column:remark;type:varchar(255);comment:Remark Info" json:"remark"`

    MoreInfo string `gorm:"->" json:"moreInfo"` // Non-table field

}

gormDB.Select("*, 'testMoreInfoVal' AS more_info").Where(&test).Find(&test)

If you are using AutoMigration then the problem will be that a more_info column will be created in your table, though Gorm will prevent writing to that column when using the struct.

What you could do in that case is use a new struct which embeds the Test struct like so:

type Test struct {
    ID     string `gorm:"column:id;type:varchar(32);primaryKey;comment:Unique ID" json:"id"`
    Name   string `gorm:"column:name;type:varchar(255);comment:Name Info" json:"name"`
    Remark string `gorm:"column:remark;type:varchar(255);comment:Remark Info" json:"remark"`
}

type TestExt struct{
    Test 
    MoreInfo string `gorm:"->" json:"moreInfo"`
}

testext := TestExt{}
gormDB.Model(&Test{}).
    Select("*, 'testMoreInfoVal' AS more_info").
    Where(Test{ID: "0000000001"}).
    Find(&testext)
Related