Gorm: Select all rows and include relations

Created on 4 Jan 2017  路  2Comments  路  Source: go-gorm/gorm

Hello!
I cant find any info about how to select all objects with relative (has many)
I have those models:

type NotificationModel struct {
    ID        uint       `gorm:"primary_key" json:"id"`
    Title     string     `gorm:"size:65535" json:"title"`
    Body      string     `gorm:"size:65535" json:"body"`
    Regions   []Region   `gorm:"ForeignKey:ID"`
    Zones     []Zone     `gorm:"ForeignKey:ID"`
    CreatedAt time.Time
    UpdatedAt time.Time
    DeletedAt *time.Time `sql:"index"`
}

type Region struct {
    ID     uint   `gorm:"primary_key"`
    Region string `gorm:"size:20"`
}

type Zone struct {
    ID   uint   `gorm:"primary_key"`
    Zone string `gorm:"size:20"`
}
models := []NotificationModel {}
db.Find(&models)

This sample code return some Notifications, but region and zone fields will nil.
(note: region and zone tables has rows with id=notification.id)

Is it possible select all notifications with regions and zones with a small count of calls to the db?
Or need forEach all notifications and select region/zone? (it may cause some mysql performance problem)

Most helpful comment

http://jinzhu.me/gorm/crud.html#query

models := []NotificationModel {}
db.Preload('Zones').Preload('Regions').Find(&models)

All 2 comments

http://jinzhu.me/gorm/crud.html#query

models := []NotificationModel {}
db.Preload('Zones').Preload('Regions').Find(&models)

@rendom that only results a list of Zones & Regions of the given model. I was hoping more of an append to the model

[{ modelA: "Val", modelB: [{ test: "Val" }] }]

Was this page helpful?
0 / 5 - 0 ratings

Related issues

alanyuen picture alanyuen  路  3Comments

koalacxr picture koalacxr  路  3Comments

bramp picture bramp  路  3Comments

corvinusy picture corvinusy  路  3Comments

rfyiamcool picture rfyiamcool  路  3Comments