go-gorm / gorm

The fantastic ORM library for Golang, aims to be developer friendly

Home Page:https://gorm.io

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Many to many preload no working, is it a bug?

robertoneto-senior opened this issue · comments

Your Question

I have this models:

Order struct {
    ID       string `gorm:"size:191;index"`
    Customer string
    Date     time.Time
    Items    []OrderItem `gorm:"many2many:order_items;"`
    Total    float64
}

Product struct {
    ID          string `gorm:"size:191;index"`
    Description string
    Price       float64
}

OrderItem struct {
    ID        string `gorm:"size:191;index"`
    OrderID   string `gorm:"size:191;index"`
    Order     Order
    ProductID string `gorm:"size:191;index"`
    Product   Product
    Price     float64
    Quantity  int
    Total     float64
}

When I run this query:

var orders []Order
gormDBInstance.Debug().Preload("Items").Preload("Items.Product").Find(&orders)

I'm geting this debug log output:

[3.324ms] [rows:2] SELECT * FROM `order_items` WHERE `order_items`.`order_id` = '046299c9-2611-4562-aac2-3fbd3f9eb812'
[9.025ms] [rows:1] SELECT * FROM `orders`
  • Note that the items select returns 2 rows so as 1 row for the master record order.
  • Note that there is no select for items product.

At the end I'm getting this result object:

[{"ID":"046299c9-2611-4562-aac2-3fbd3f9eb812","Customer":"Roberto","Date":"2024-07-12T02:59:07-03:00","Items":[],"Total":15025}]

Expected answer

I expected to receive the order and it items with each product on each item preloaded.
Am I doing something wrong? The models are defined correctly? Is this a potential bug?

Update your OrderItem struct as follows:
type OrderItem struct {
ID string gorm:"size:191;index"
OrderID string gorm:"size:191;index"
Order Order gorm:"foreignKey:OrderID;references:ID"
ProductID string gorm:"size:191;index"
Product Product gorm:"foreignKey:ProductID;references:ID"
Price float64
Quantity int
Total float64
}

If this doesn't work then maybe you doesn't need many2many relationship and try Items []OrderItem gorm:"foreignKey:OrderID;references:ID"``

Also you have: var orders []Order gormDBInstance.Debug().Preload("Items").Preload("Items.Product").Find(&orders) which should be: var orders []Order gormDBInstance.Debug().Preload("Items.Product").Find(&orders) you don't need Items Preload again, Items.Product Preload Items and Items.Product also

Hi.

Thanks @Nicolas-ggd , I just removed the many2many tag and it started to work. I didn't even need to create the foreignKey tags, just removing the many2many.