How to populate and embedded array with gorm? - go

I have 2 structs with data like this:
type User struct {
Pics Pic[]
}
type Pic struct {
Id int
UserId int64
}
Although everytime I insert an User, Each of the pics are inserted on their table everytime I find the users, pics are not populated:
var users []User
db.Limit(pagesize).Where("updated_at > ?", date).Find(&users)
Am I doing something wrong?

Your models (the structs) don't really make sense because User have a Pic array indicates a 'one to many' user to pics relationship however your user has no id property itself and there for cannot be related to items on the Pic table.
User should have a property Id which will be it's primary key and UserId is a foreign key on Pic that relates to it. Without the 'relation' between these two tables/entities there's no way you're going to return pics by querying users.
I'm not sure what all you need to do to make your code work since the example is incomplete but the first thing you need is an Id property which you should designate as a Primarykey with gorm annotations. You also should have annotations on the Pic struct saying UserId is a foreign key and Id is it's primary key.
Also, just fyi your array is not embedded. Embedding is a language feature which you're not using, if you embed the property it has no name and it's properties can be accessed directly from an instance of the embedding type.

I had these issues once. Then I used Join function.
See my example that works just fine:
type FileType struct {
Id int
}
type File struct {
Id int
FileType `xorm:"extends"`
}
file := File{Id: id}
has, err := eng.
Join("INNER", "FileType", "FileType.IdFileType = File.IdFileType").
Get(&file)

You probably know by now. You got to think as if you are creating a SQL table with 1-to-many relationship. Here is an example:
type Entry struct {
ID int
Name string
...
ContainerID int
}
type Container struct {
ID int
Tag int
Name string
...
Entries []Entry `gorm:"foreignkey:ContainerID"`
}
The trick is to populate it. I am yet to find how to make it in one try. For every such dependency, you got to run something like:
c := getContainerFromDB(...)
if err := getROConn().Model(c).Related(&c.Entries, "Entries").Error; err != nil {
return errors.Wrap(err, "error getting container field")
}

Try Preload
db.Limit(pagesize).Where("updated_at > ?", date).Preload("Pics").Find(&users)

Related

Foreign Key Constraint in gorm

I want to create a Booking-Class relationship, where every Booking can be assigned only one Class.
type Class struct {
Id int `json:"id"`
Name string `json:"name"`
}
type Booking struct {
Id int `json:"id"`
User string `json:"user"`
Members int `json:"members"`
ClassId int `json:"classid"`
}
I understand that it is similar to gorm's "belongs-to" relationship explained here https://gorm.io/docs/belongs_to.html but I was wondering if it's possible to achieve "foreign key constraint" without defining the field of type Class inside the Booking model (only ClassId int). To make sure that non-existent ClassId-s are used I defined functions:
func Find(slice []int, val int) bool {
for _, item := range slice {
if item == val {
return true
}
}
return false
}
func GetClassKeys(d *gorm.DB) []int {
var keys []int
rows, _ := d.Raw(`SELECT id
FROM classes`).Rows()
defer rows.Close()
for rows.Next() {
var key int
rows.Scan(&key)
keys = append(keys, key)
}
return keys
}
And perform this check before creating/updating a booking:
if !Find(GetClassKeys(db), booking.ClassId) {
log.Println("Wrong class id value")
return
}
But this doesn't handle the case of removed class id (which regular databases do automatically). I was wondering is there a way to achieve a normal database foreign key functionality with gorm by simply referencing the primary key of Class in a User model? Thanks in advance
I don't think the Migrator tool will help you because it assumes you're going to use the default Gorm patterns for defining relationships, and you've explicitly decided NOT to use these.
The only remaining option is to manage the constraint yourself, either through an SQL script or easier, some custom queries you run alongside your AutoMigrate call:
import "gorm.io/gorm/clause"
// somewhere you must be calling
db.AutoMigrate(&Class{}, &Booking{})
// then you'd have:
constraint := "fk_booking_classid"
var count int64
err := db.Raw(
"SELECT count(*) FROM INFORMATION_SCHEMA.table_constraints WHERE constraint_schema = ? AND table_name = ? AND constraint_name = ?",
db.Migrator().CurrentDatabase(),
"bookings",
constraint,
).Scan(&count).Error
// handle error
if (count == 0) {
err := db.Exec(
"ALTER TABLE bookings ADD CONSTRAINT ? FOREIGN KEY class_id REFERENCES classes(id)",
clause.Table{Name: constraint},
).Error
// handle error
}
Of course, this negates the advantage of having an automated migration (which means when things change like the field name, the constraint will be updated without changes to the migration code).
I'd be looking at why you don't want to define the foreign key as gorm expects, as this smells of you trying to use the database model directly as your JSON API Request/Response model, and that usually doesn't lead to a good end :)

Query with 'has one' association (one-to-one)

I'm playing a bit with Gorm while I'm trying to decide which ORM library fit the most for my needs.
Important to mention that I'm currently working with Sqlite.
Following the guide I created two structs:
type Color struct {
gorm.Model
UserID uint
Name string
}
//User struct define a basic user model
type User struct {
gorm.Model
Username string
Email string
FirstName string
LastName string
Password string
CreationDate time.Time
DOB time.Time
IgnoreMe int `gorm:"-"` // Ignore this field
Color Color `gorm:"foreignkey:ColorRefer"`
ColorRefer uint
}
when I'm creating a DB with
func CreateTables() {
user := dm.User{}
color := dm.Color{}
GormDB.CreateTable(&color)
GormDB.CreateTable(&user)
GormDB.Model(&user).AddForeignKey("ColorRefer", "colors(id)", "CASCADE", "CASCADE")
}
or with:
func CreateTables() {
GormDB.AutoMigrate(&dm.User{},&dm.Color{})
}
Sadly it's not working as I would of expect and create the foreign key automatically, but it's works when I do it manually.
My main problem is when I'm trying to query Users
//QueryByStructExample query users table by the struct non-zero (non-default) fields.
func QueryByStructExample(userStruct dm.User) []dm.User {
var results []dm.User
GormDB.Where(userStruct).Find(&results)
return results
}
I created the following function in a try to query users by email with the color property which is my color struct and I tried to play with a lot with the Model,Related and the Association functions, and nothing seems to work and (I'm avoiding to use join by purpose).
The end result is that it query my User but without the color (only with the ID in my colorRefer)
any suggestion?
Do you mean to preload the Color struct? If yes did you try to query it like that
GormDB.Preload('Color').Where(userStruct).Find(&results)

How to update with a many-to-many relationship

I'm facing a difficulty with the go orm gorm:
I have a structure like this:
type Data struct {
gorm.Model
UserID int `json:"user_id,omitempty"`
AnswerID int `json:"answer_id,omitempty"`
Entities []Entity `gorm:"many2many:data_entities;"`
}
type Entity struct {
gorm.Model
Name string
}
And now, either if I do:
db.Model(&data).Where(Data{AnswerID: data.AnswerID}).Assign(&data).FirstOrCreate(&data)
Or
db.Model(&data).Where(Data{AnswerID: d.AnswerID}).Update(&data)
My many-to-many fields aren't updated but created... Leading to duplications if already exists.
If I try to play with the Related() function, it simply stop updating the foreign field.
Is there a way to update or create properly every tables linked?
I do it like this:
To update your data just pass a struct with only the fields you wanna update:
db.Model(&data).Updates(Data{UserID: 2, AnswerID: 2})
and to add new entities:
db.Model(&data).Association("Entities").Append([]*Entity{&Entity{Name: "mynewentity"}})
The way I handled it is using a custom join table and just inserting or deleting the rows manually.
type DataEntity struct {
DataID string `gorm:"primaryKey"`
EntityID string `gorm:"primaryKey"`
CreatedAt time.Time
DeletedAt gorm.DeletedAt
}
set up the join table
err := db.AutoMigrate(&Data{}, &Entity{}, &DataEntity{})
err = db.SetupJoinTable(&Data{}, "Entities", &DataEntity{})
Then for deleting entities:
db.Unscoped().Model(&Data).Association("Entities").Clear()
To add entities:
dataEntities := []DataEntity{DataEntity{DataID:dataid,EntityID:eid}}
dbConnection.Create(&dataEntites)
Slightly cumbersome but it's the only solution I've found so far.
So far the only I found is this one:
db.Table("entities").
Where(
"id in (?)",
db.Table("data_entities").
Select("entity_id").
Where(
"data_id = ?",
data.ID,
).
QueryExpr(),
).
Where("entity_name = ?", *entityName).
Update(&data.Entity)
But I found 2 problems here:
1) Impossible to do a deeper subrequest:
Select("entity_id").
Where(
"data_id = ?",
data.ID,
)...
Won't work if instead of data.ID I want to go deeper with an other sub-request.
2) in case of multiple many-2-many I assume I would need to duplicate the query.
I was able to resolve according to the documentation using the Association.Replace
http://gorm.io/docs/associations.html#Replace-Associations
db.Debug().First(&data)
data.Name = "New Name"
db.Save(&data).Association("Entities").Replace([]Entity{{Name: "mynewentity"}})

golang gorm update associations on save

is there a way to automatically remove associations when an object is saved?
something like this:
type Parent struct {
gorm.Model
Name string
Children []*Child
}
type Child struct {
gorm.Model
Name string
ParentID uint
}
func myFunc(db *gorm.DB) {
p := &Parent{Name: "foo", Children:[]*Child{ {Name:"Bar"}, {Name:"Foobar"}}}
db.Save(&p)
p.Children = p.Children[1:]
db.Save(&p) // both children still exist in the database. i'd like the first child to be deleted here
}
`
I've found some tricks with db.Model(&Parent).Association("Children").Clear(), but that just sets the ParentID value to NULL, rather than deleting the record. Is there a simple way of doing this?
Many thanks in advance :)
I think you just simply use the physical batch delete like following code:
db.Unscoped().Where("parent_id = ?", p.ID).Delete(Child{})
Hope this help.

gorm golang one2many same table

I'm trying to create a self-reference in a (my)sql table using golang gorm. At the moment my code looks like this:
type Person struct {
gorm.Model
Name string
Children []*Person `gorm:"ForeignKey:ParentID"`
ParentID uint
}
func main() {
/* code to get database connection omitted */
p := &Person{Name:"Sally"}
db.Create(p)
children := []*Person{ {Name:"Jane", ParentID:p.ID},
{Name:"Tom", ParentID:p.ID}}
for _, child := range children {
db.Create(child)
}
var children2 []*Person
db.Model(p).Related(children2, "ParentID")
}
The code is failing with an error "reflect.Value.Set using unaddressable value".
Does anybody know how to get this relationship working using go gorm?
Many thanks in advance :)
Fortunately gorm have added lately this feature (reference: here).
In your case should be like this:
type Person struct {
gorm.Model
Name string
Children []*Person `gorm:"many2many: children;association_jointable_foreignkey:children_id"`
}

Resources