One-to-many association get data from the one table - go

I'm new to Golang and Gorm, and I couldn't find the anwswer. In a rest api, I want my json to come with values from the one table relation.
type Product struct {
gorm.Model
Name string
Description string
Weight string
TypeID uint
}
type Type struct {
ID string `gorm:"primaryKey;"`
Name string
Product []Product
}
and I want my Product json to come with the ID and Name from Type.
but this doesn't work.
var product Product
id:=1
db.Preload("Type").First(&product, id)
Do I have to do something like this in the struct?
type Product struct {
gorm.Model
Name string
Description string
Weight string
Type Type
}

If you want to load Type.ID and Type.Name into Product.ID and Product.Name, you need to specifically select fields from two tables:
var product Product
id:=1
db.Joins("JOIN types ON types.id = products.type_id"). Select("types.id, types.name, products.description, products.weight, products.type_id").First(&product, id)
If you want to separate Type fields into a separate field in the Product struct, you need to make the following changes:
type Product struct {
gorm.Model
Name string
Description string
Weight string
TypeID uint
Type Type
}
var product Product
id:=1
db.Preload("Type").First(&product, id)
Here, all of the Type fields will be loaded into the Product.Type field.

Related

How to get empty string for datatypes.Date in Gorm if value in database is null

I have this model struct:
type User struct {
ID uint `json:"id" gorm:"primaryKey"`
Name string `json:"name"`
BirthDate datatypes.Date `json:"birthDate" gorm:"default:null"`
}
In field BirthDate I am using custom data type datatypes.Date provided by Gorm
The problem is, it shows this value 0001-01-01T00:00:00Z in json response, while inside the database the value of BirthDate is null.
What I want is it should result in empty string if null, How to achive that?

How do I use custom preload in gorm

I have these 2 structs
type User struct {
gorm.Model
Name string
CompanyID int
Company Company
}
type Company struct {
gorm.Model
Name string
Adress string
}
I want to get users and preload their companies but I don't want to get the Adress field I tried the custom preload like bellow and I tested it in postman . the query returned all the fields but for adress I get an empty string , the reason why this is happening is that when storing the result in the user struct golang automatically initialize all the fields and the field adress get returned with its initial value which is an empty sting
var user []User
db.Table("users").Preload("Company",func(db *gorm.DB) *gorm.DB {
return db.Select("ID" ,"Name")
}).Find(&user)
what should I do to only have the name and id but not the adress
If your server exports the result as json you could add the json tag omitempty as such:
type Company struct {
gorm.Model
Name string
Adress string `json:"omitempty"`
}
That way the address field will not be included if it is an empty string.

Gorm query without gorm.Model columns

How can I omit the columns that come from the gorm.Model. E.g. CreatedDate, modifiedDate.
Consider the following model:
type User struct{
gorm.Model
Firstname string
Lastname string
}
Now I can select specific column with:
db.Select("Firstname").Find(&users)
However, while it excludes the Lastname column, it does not exclude the columns that come from the gorm.Model. So the result would look something like:
[{"ID":0,"CreatedAt":"0001-01-01T00:00:00Z","UpdatedAt":"0001-01-01T00:00:00Z","DeletedAt":null,"Firstname":"Foobar"}]
I want only the Firstname column.
You can define your User type without including gorm.Model struct
type User struct{
Firstname string
Lastname string
}
Alternatively, you can use two types, one with gorm.Model and the second without it. You can use the latter when retrieving values without gorm.Model properties.

Map value from one column into another in separate tables using Gorm

Given the following one-to-many relationship (One Receipt has many LineItem's), I would like to map the Price field from the Receipt table into the Price field of LineItem table (for each LineItem in Product).
Receipt Schema
type Product struct {
ID uint `json:"id"`
TotalPrice float64 `json:"total"`
LineItems []LineItem `json:"lineItems"`
}
LineItem Schema
type LineItem struct {
ID uint `json:"id"`
ProductID uint `json:"productID"`
Price float64 `json:"price"`
}
I'm currently using gorm, an ORM for Go, but I can't find the functionality to support what I'm looking for.
Assuming that you have 3 tables/models, Receipt, Product, and LineItem, you can add field that reference Product in LineItem model like so :
type Receipt struct {
ID uint `json:"id"`
TotalPrice float64 `json:"total"`
LineItems []LineItem `json:"lineItems"`
}
type Product struct {
ID uint `json:"id"`
Price float64 `json:"price"`
}
type LineItem struct {
ID uint `json:"id"`
ProductID uint `json:"productID"`
Product *Product `json:"product"`
}
Then you can query Receipt while populating LineItems field as well as Product field in each LineItem by using gorm's Preload feature:
db.Preload("LineItems").Preload("LineItems.Product").Find(&receipt)
This way you will have the price info in each LineItem accessible through Product field:
for _, li in receipt.LineItems {
fmt.Println(li.Product.Price)
}

One-to-many recursive relationship in GORM

I need to have an Organization which have relation to parent one. Something like this:
type Organization struct {
gorm.Model
Parent *Organization `gorm:"ForeignKey:ParentId"`
Name string `gorm:"size:30"`
Description string `gorm:"size:100"`
}
I want to have ParentId field which will be referenced to id field in the same table. But as I see there is no field and relation.
How can I fix it ?
I have solved it like this, but I am not sure that it is a correct way:
type Organization struct {
gorm.Model
Parent *Organization
ParentId int `gorm:"TYPE:integer REFERENCES organizations"`
Name string `gorm:"size:30"`
Description string `gorm:"size:100"`
}

Resources