Open Mrbeyond opened 2 years ago
This issue has been automatically marked as stale because it has been open 360 days with no activity. Remove stale label or comment or this will be closed in 180 days
This is still an active issue for me
First of all, before the latest version, we do not support nested preload, and secondly, the currently supported method should be
Preload("Work", func(db *gorm.DB) *gorm.DB {
...
}). Preload("Work.Project")
https://github.com/go-gorm/gorm/pull/6137
cc @black-06
@a631807682 thanks for the pointer to that PR! Does the new syntax allow a limit to be applied to the Project
in Work.Project
?
DB.Where("email = ?", "user").
Preload("Work").
Preload("Work.Project", func(tx *gorm.DB) *gorm.DB {
return tx.Limit(1).Order("projects.id DESC")
}).
Find(&rst).Error
SQL is
SELECT * FROM `projects` WHERE `projects`.`work_id` IN (1,2) ORDER BY projects.id DESC LIMIT 1
SELECT * FROM `works` WHERE `works`.`user_id` = 1
SELECT * FROM `users` WHERE email = "user"
But it only has one Project in all Works.
Try group by work_id
:
DB.Debug().
Where("email = ?", "user").
Preload("Work").
Preload("Work.Project", func(tx *gorm.DB) *gorm.DB {
return tx.Group("work_id")
}).
Find(&rst).Error
// SELECT * FROM `projects` WHERE `projects`.`work_id` IN (1,2) GROUP BY `work_id`
It seems that we have no way to set the limit number of each subset in a query, @mnussbaum what is the raw sql you want?
Your Question
I want to perform a limit on a nested preload to improve performance. The limit works on the total count on the children but I want the limit to work on each distinct owner.
The models are:
Query without Limit:
Result:
Query used to Limit Projects assocatied with Work to just one:
Result:
The Issue:
It limits total project fetched to just one instead one to each work.
Expected answer:
I seriously need help with this.
Thanks.