Can associations in gorm go both ways? - go

Can I make associations in gorm go both ways?
i.e.
type Store struct {
ID int
Products []Product
}
type Product struct {
ID int
StoreID int
Store Store
}
So a Store has many Products, and a Product belongs to a Store.
Is this correct?

Related

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

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.

Should I explicitly create a relation symmetrical to "Belongs To" or "Has Many"?

I am new to ORM (and GORM) so apologies if this is an obvious question, but it does not seem to be covered by the documentation.
I will be using the examples from the documentation as a base to my questions
Question 1: Belongs To
// `User` belongs to `Company`, `CompanyID` is the foreign key
type User struct {
gorm.Model
Name string
CompanyID int
Company Company
}
type Company struct {
ID int
Name string
}
A User belongs to one Company only → this is handled by the code
above
A Company has many User → is this implied by the code
above? Or should I add somehow a relation O2M in Company?
Question 2: Has Many
// User has many CreditCards, UserID is the foreign key
type User struct {
gorm.Model
CreditCards []CreditCard
}
type CreditCard struct {
gorm.Model
Number string
UserID uint
}
A User has 1+ CreditCard→ this is handled by the code
A CreditCard can belong to several users (say, a shared family CC) → is it implied? (if not: how to set up the O2M relationship).
Or is it, instead, a case where a CreditCard is explicitly configured to belong to only one user?
Q1: Based on how you defined your structs, you don't need an explicit O2M relationship in the Company struct, but when loading Company details, if you want to load all users that are assigned to that specific company, you need to add that field as well. It will need an additional function call like Preload or Joins, but you shouldn't need an explicit definition of this relationship.
type Company struct {
ID int
Name string
Users []User
}
Q2: The way the relationship is defined now, it is configured so that a CreditCard belongs to only one user. If you want a many2many relationship, you need to specify the relation table. There is more documentation on it here, but it should look something like this:
type User struct {
gorm.Model
CreditCards []CreditCard `gorm:"many2many:users_creditcards"`
}
type CreditCard struct {
gorm.Model
Number string
}

How to update with a has many relationship

I use the gorm with the has many。
This is my model
type Pro struct {
Model
TaxRate []TaxRate `json:"taxRate" gorm:"constraint:OnUpdate:CASCADE;"`
}
type TaxRate struct {
ID uint
Tax float64
ProjectID uint
}
but when I update the project, I found that the TaxRate just insert the record not update.
This is my update operation
result:=pRepo.db.Session(&gorm.Session{FullSaveAssociations: true}).Updates(p)
According to the gorm documentation on has-many relationships (https://gorm.io/docs/has_many.html) the automatic relation needs to be structnameID, so in your case ProID (the owner struct is called Pro and not Project). Either rename the struct or the reference or add gorm:"foreignKey:ProjectID" as tag:
type Pro struct {
Model
TaxRate []TaxRate `json:"taxRate" gorm:"foreignKey:ProjectID;constraint:OnUpdate:CASCADE;"`
}

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)
}

Entity association to itself with one-to-many relationships

I use GORM to build model associations in Golang and I have a struct named Category. A category can have many children categories and it may have a parent category:
type Category struct {
Name string `json:"name"`
Parent Category `json:"parent_category"`
ParentGroupID uint `json:"parent_group_id"`
Children []Category `json:"children_categories"`
}
For this struct, I got an error for Invalid recursive type Category. I checked the GORM documentation but did not find anything helpful there. Any ideas how to model this kind of relation with GORM?
You must declare Parent as *Category (a pointer to Category) instead of Category.
type Category struct {
Name string `json:"name"`
Parent *Category `json:"parent_category"`
ParentGroupID uint `json:"parent_group_id"`
Children []Category `json:"children_categories"`
}
How does compiler know what the size of Parent is. A pointer's size is known, but how big is something that contains itself? (And the inner struct contains itself as well, as does the inner inner struct, and so on.)
Reference: https://stackoverflow.com/a/8261789/4794989

Resources