Skip to content

How to join nested tables #5280

@sintanial

Description

@sintanial

Your Question

I have models like this:

package models

type ItemAsset struct {
	ID int32 `gorm:"primary_key;AUTO_INCREMENT;column:id;type:int;" json:"id"`
	ItemID string `gorm:"column:item_id;type:varchar;size:36;" json:"item_id"`
}

type ItemSet struct {
	ID uint32 `gorm:"primary_key;AUTO_INCREMENT;column:id;type:uint;" json:"id"`
}

type Item struct {
	ID int32 `gorm:"primary_key;AUTO_INCREMENT;column:id;type:int;" json:"id"`
	ItemID string `gorm:"column:item_id;type:varchar;size:36;" json:"item_id"`
	SetID null.Int `gorm:"column:set_id;type:uint;" json:"set_id"`
}

type PlayerItem struct {
	ID int32 `gorm:"primary_key;AUTO_INCREMENT;column:id;type:int;" json:"id"`
	PlayerID string `gorm:"column:player_id;type:varchar;size:128;" json:"player_id"`
	ItemID string `gorm:"column:item_id;type:varchar;size:36;" json:"item_id"`
	ItemLevelID null.Int `gorm:"column:item_level_id;type:uint;" json:"item_level_id"`
}

type ItemLevel struct {
	ID uint32 `gorm:"primary_key;AUTO_INCREMENT;column:id;type:uint;" json:"id"`
	ItemID string `gorm:"column:item_id;type:varchar;size:36;" json:"item_id"`
}

And then i have another structure which combine all structure with relations

package entity

type Item struct {
	models.Item
	ItemAsset *models.ItemAsset `gorm:"foreignKey:ItemID;references:item_id" json:"item_asset"`
	ItemSet   *models.ItemSet          `gorm:"foreignKey:ID;references:set_id" json:"item_set"`
}

type PlayerItem struct {
	models.PlayerItem
	Item      Item       `gorm:"foreignKey:ItemID;references:item_id" json:"item"`
	ItemLevel *models.ItemLevel `gorm:"foreignKey:ItemLevelID;references:id" json:"item_level"`
}

So my question is, how can i join nested models when i fetch entity.PlayerItem ?

Query like this is not working :(

db.
		Joins("ItemLevel").
		Joins("Item").
		Joins("Item.ItemAsset").
		Joins("Item.ItemSet").
		Find(&items).

Yes, of course i know about Preload ! But it's generate separate query, but i want to join nested structure by LEFT JOIN query !

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions