Is it possible to use many to many between 3 models? (GORM) - go

Is it possible to use many to many between 3 models?
I have 3 models I want to join into a bridge table "client_operator_role"
Operator
type Operator struct {
gorm.Model
Title string `gorm:"unique;not null" validate:"required,min=1,max=100"`
Email string `gorm:"not null;unique" validate:"required,email"`
Mobile string `gorm:"not null" validate:"required,min=7,max=15,numeric"`
Last_online time.Time `gorm:"default:null" validate:"omitempty"`
Last_ip string `gorm:"default:null" validate:"omitempty,ip"`
Clients []*Client `gorm:"many2many:client_operator_role;"`
Cli_ids []string `gorm:"-:all" validate:"omitempty,dive,numeric"` // placeholder field, wont be part of table
GoadminCustomUser GoadminCustomUser `validate:"omitempty,dive"`
}
Client
type Client struct {
gorm.Model
Name string `gorm:"unique;not null" validate:"required,min=1,max=30"`
Kyc_status string `gorm:"not null" validate:"required,min=1,max=30"`
Kyc_remarks string `gorm:"default:null" validate:"omitempty,min=0,max=200"`
Operators []*Operator `gorm:"many2many:client_operator_role;"`
Op_ids []string `gorm:"-:all" validate:"omitempty,dive,numeric"` // placeholder field, wont be part of table
Users []User
}
Role
type GoadminRole struct {
ID uint `gorm:"primaryKey"`
Name string
Slug string
CreatedAt time.Time
UpdatedAt time.Time
Operators []*Operator `gorm:"many2many:client_operator_role;"`
}
Gorm docs state many2many is only for 2 models. Is there a workaround to join these three?

Related

Gorm UUID foreign key - belongs to

I'm trying to create a belongs to relation between two database tables, using GORM, my code is the following:
type Shop struct {
ID uuid.UUID `json:"id" gorm:"primaryKey;type:uuid"`
Name string `json:"name" gorm:"not null" validate:"required"`
City string `json:"city" gorm:"not null" validate:"required"`
State string `json:"state" gorm:"not null" validate:"required"`
}
type Employee struct {
ID uuid.UUID `json:"id" gorm:"primaryKey;type:uuid"`
FirstName string `json:"first_name" gorm:"not null" validate:"required"`
LastName string `json:"last_name" gorm:"not null" validate:"required"`
Email string `json:"email" gorm:"not null;unique" validate:"required,email"`
Password string `json:"password" gorm:"not null" validate:"required"`
Active bool `json:"active" gorm:"not null;default:false"`
ShopId uuid.UUID `json:"shop_id" gorm:"type:uuid"`
Shop Shop `gorm:"foreignKey:ShopID"`
}
When I run the migrations, this error pops up:
[error] invalid field found for struct .../.../.../api/models.Employee's field Shop: define a valid foreign key for relations or implement the Valuer/Scanner interface
I've found some references using number primary keys and they seem to work fine, but I can't find any solution to work with uuids...
I'm not sure, but what I understand of the message error is that the type uuid.UUID doesn't have implemented the methods for the interfaces Valuer and Scanner.
You should create your own type UUID, which can be something like this:
type UUID uuid.UUID
func(id UUID) Value() (driver.Value, error) {
return id.String(), nil
}
func (id *UUID) Scan(value interface{}) error {
dbID, ok := value.(string)
if !ok {
return errors.New("id scan: invalid value")
}
*e = uuid.MustParse(dbID)
return nil
}
And use it on your struct's definitions:
type Shop struct {
ID UUID `json:"id" gorm:"primaryKey;type:uuid"`
//...
}

How to delete association (many2many)?

Strange behaviour deleting association happened.
The query generated an extra condition which i did not add.
type Client struct {
gorm.Model
Name string `gorm:"unique;not null" validate:"required,min=1,max=30"`
Kyc_status string `gorm:"not null" validate:"required,min=1,max=30"`
Kyc_remarks string `gorm:"default:null" validate:"omitempty,min=0,max=200"`
Operators []*Operator `gorm:"many2many:client_operators;"`
Op_ids []string `gorm:"-:all" validate:"omitempty,dive,numeric"` // placeholder field, wont be part of table
}
type Operator struct {
gorm.Model
Title string `gorm:"unique;not null" validate:"required,min=1,max=100"`
Email string `gorm:"not null" validate:"required,email"`
Mobile string `gorm:"not null" validate:"required,min=7,max=15,numeric"`
Last_online time.Time `gorm:"default:null" validate:"omitempty"`
Last_ip string `gorm:"default:null" validate:"omitempty,ip"`
Clients []*Client `gorm:"many2many:client_operators;"`
Cli_ids []string `gorm:"-:all" validate:"omitempty,dive,numeric"`
}
// find operators related to client
var client_query *Client
DBconnection.Where("id = ?", pk).Preload("Operators").First(&client_query)
// delete operators related to client
DBconnection.Model(&Client{}).Where("client_id = ?", pk).Association("Operators").Delete(&client_query.Operators)
I expect the deletion to be:
[2.000ms] [rows:0] DELETE FROM `client_operators` WHERE client_id = 5 AND `client_operators`.`operator_id` = 1
OR
[2.000ms] [rows:0] DELETE FROM `client_operators` WHERE `client_operators`.`client_id` = 5 AND `client_operators`.`operator_id` = 1
However it currently does:
[2.000ms] [rows:0] DELETE FROM `client_operators` WHERE client_id = 5 AND `client_operators`.`client_id` IN (NULL) AND `client_operators`.`operator_id` = 1
It adds the extra condition of " AND `client_operators`.`client_id` IN (NULL) "
I tried Association().Clear() and did not do anything too.
This is happening because you're passing &Client{} to Model.
Looking at gorm docs you need to construct a client with a valid Id first like this:
type Client struct {
gorm.Model
Name string `gorm:"unique;not null" validate:"required,min=1,max=30"`
Kyc_status string `gorm:"not null" validate:"required,min=1,max=30"`
Kyc_remarks string `gorm:"default:null" validate:"omitempty,min=0,max=200"`
Operators []*Operator `gorm:"many2many:client_operators;"`
Op_ids []string `gorm:"-:all" validate:"omitempty,dive,numeric"` // placeholder field, wont be part of table
}
type Operator struct {
gorm.Model
Title string `gorm:"unique;not null" validate:"required,min=1,max=100"`
Email string `gorm:"not null" validate:"required,email"`
Mobile string `gorm:"not null" validate:"required,min=7,max=15,numeric"`
Last_online time.Time `gorm:"default:null" validate:"omitempty"`
Last_ip string `gorm:"default:null" validate:"omitempty,ip"`
Clients []*Client `gorm:"many2many:client_operators;"`
Cli_ids []string `gorm:"-:all" validate:"omitempty,dive,numeric"`
}
// find operators related to client
var client_query *Client
DBconnection.Where("id = ?", pk).Preload("Operators").First(&client_query)
// delete operators related to client
DBconnection.Model(&Client{ID: pk}).Association("Operators").Delete(&client_query.Operators)

Custom Gorm preloading does not fetch data

I have a query that fetches rows from jobs table and its author (each job has an author), but I want to select specific fields.
type User struct {
ID uint `gorm:"primarykey" json:"-"`
UUID uuid.UUID `gorm:"type:uuid not null" json:"-"`
Email string `gorm:"type:varchar(255); not null" json:"email"`
Name string `gorm:"type:varchar(255); not null" json:"name"`
AvatarURL string `gorm:"type:varchar(255); not null" json:"avatar_url"`
Provider string `gorm:"type:varchar(255); not null" json:"provider"`
ProviderID string `gorm:"type:varchar(255); not null" json:"-"`
Jobs []Job `json:"-"`
}
type Job struct {
ID uint `gorm:"primarykey" json:"id"`
Title string `gorm:"type:varchar(255); not null" json:"title"`
Content string `gorm:"not null" json:"content"`
UserID uint `json:"-"`
User User `json:"author"`
}
func (jobRepo repository) FindAll() ([]entity.Job, error) {
var jobs []entity.Job
if dbc := jobRepo.db.Preload("User", func(db *gorm.DB) *gorm.DB {
return db.Select("Name", "Email")
}).Find(&jobs); dbc.Error != nil {
return nil, dbc.Error
}
return jobs, nil
}
The custom preload does not behave as desired. If I do not specify concrete fields, the query works and returns everything. Otherwise, If I specify some fields, it returns nothing.
This is because you didn't select primary key. Add "ID" into select clause:
func(db *gorm.DB) *gorm.DB {
return db.Select("ID", "Name", "Email")
}
Otherwise GORM doesn't know how to join users to jobs.

How to solve gorm many2many error1062

I have a many2many relation between news and tag. Whenever I tried to assign news to a tag it gives me an error Error 1062: Duplicate entry '5' for key 'news_id'
My model look like this:
type Tag struct {
ID uint64 `json:"id" gorm:"primary_key;unique;AUTO_INCREMENT"`
Title string `json:"title" gorm:"varchar(20)" binding:"required"`
News []*News `json:"news" gorm:"many2many:news_tags;association_foreignkey:ID;foreignkey:ID"`
CreatedAt time.Time `json:"created_at" gorm:"column:created_at"`
UpdatedAt time.Time `json:"updated_at" gorm:"column:updated_at"`
}
// News model
type News struct {
ID uint64 `json:"id" gorm:"primary_key;unique;AUTO_INCREMENT"`
Title string `json:"title" gorm:"varchar(20)" binding:"required"`
Body string `json:"body" gorm:"varchar(500)" binding:"required"`
Status string `json:"status" gorm:"varchar(5)"` // 1 = publish; 2 = draft; 3 = deleted;
Tags []*Tag `json:"tags" gorm:"many2many:news_tags;association_foreignkey:ID;foreignkey:ID"`
Topics []*Topic `json:"topics" gorm:"many2many:news_topics"`
CreatedAt time.Time `json:"created_at" gorm:"column:created_at"`
UpdatedAt time.Time `json:"updated_at" gorm:"column:updated_at"`
}
// My code when trying to assign new tag
func (n *News) AssignTags(tag Tag) {
db.DB().Model(n).Association("Tags").Append(tag)
}

Copy values from one struct to another in Golang

I've two structs:
type UpdateableUser struct {
FirstName string
LastName string
Email string
Tlm float64
Dob time.Time
}
type User struct {
Id string
FirstName string
LastName string
Email string
DOB time.Time
Tlm float64
created time.Time
updated time.Time
}
Through a binder I bind request data to the updateableUser struct, therefore I might have an updateableUser with only one "real" value, like uu here:
uu := UpdateableUser{Lastname: "Smith"}
Now I want to set only the not "emtpy" values from UpdateableUser to User. Can you please give me a hint or more?
I would recommend embedding the Updateable struct into the larger struct:
type UpdateableUser struct {
FirstName string
LastName string
Email string
Tlm float64
Dob time.Time
}
type User struct {
UpdateableUser
ID string
created time.Time
updated time.Time
}
func (u *User) UpdateFrom(src *UpdateableUser) {
if src.FirstName != "" {
u.FirstName = src.FirstName
}
if src.LastName != "" {
u.LastName = src.LastName
}
// ... And other properties. Tedious, but simple and avoids Reflection
}
This allows you to use UpdateableUser as an interface to make it explicit which properties can be updated.

Resources