Gorm: Nested preloading

Created on 1 Mar 2015  路  9Comments  路  Source: go-gorm/gorm

I'd like to do something like this, but I don't think it's possible:

type City struct {
    Id int
    Name string
}

type Address struct {
    HouseNumber int
    Street string

    City City
    CityId int
}

type Order struct {
    Address Address
    AddressId int

    User User
    UserId int
}

type User struct {
    Id int

    Orders []Order
}

db.Model(user).Preload("Address").Preload("Address.City").Related(&orders) // Address.City is not a relation in Order, so it's ignored

Most helpful comment

Keep in mind that this implementation uses subsequent SELECT(s). While this is great for simplicity (and perhaps multi-level caching with the correct callback configuration) ... it's also could be optimized by using JOIN statements to reduce latency to/from the server from multiple queries.

All 9 comments

Hi @nkovacs

Yes, this is not supported yet, but on the plan already.

:+1: would be lovely if gorm supports this.

I'm also looking forward to this. Any cues/ideas on how the api will be?

It will like @nkovacs's example.

db.Model(user).Preload("Address").Preload("Address.City").Related(&orders)

That would be really useful.

@jinzhu Can you confirm, this feature is working now?
https://github.com/jinzhu/gorm#nested-preloading

If it works, I think we also can update http://stackoverflow.com/questions/29230261/how-preload-a-full-hierachy-in-go-using-gorm

Hi @rtm7777

Yes, it is works already. sorry forgot to update this issue.

Keep in mind that this implementation uses subsequent SELECT(s). While this is great for simplicity (and perhaps multi-level caching with the correct callback configuration) ... it's also could be optimized by using JOIN statements to reduce latency to/from the server from multiple queries.

@jinzhu Let the take the above example. Assume there is another level province which is under city.
Can we preload province under User without pre loading address and city

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Ganitzsh picture Ganitzsh  路  3Comments

pjebs picture pjebs  路  3Comments

sredxny picture sredxny  路  3Comments

superwf picture superwf  路  3Comments

easonlin404 picture easonlin404  路  3Comments