it is so difficult to understand what you want and your problem, instead show us the code of the request that is causing the N+1 problem.
Nov 22, 2024
8
Level 7
How to eager load model custom calculated queries
I have a posts table and a content links table, currently to list posts with their external links, I fetch all posts, then for each post I submit another query, something like this:
select * from posts;
select * from "content_links" where "postable_type" = ? and "postable_id" != ? and "url" in (?, ?, ?)
select * from "content_links" where "postable_type" = ? and "postable_id" != ? and "url" in (?, ?, ?)
select * from "content_links" where "postable_type" = ? and "postable_id" != ? and "url" in (?, ?, ?)
...
and in post model my externalLinks method looks like this:
public function externalLinks(): Collection
{
return ContentLinks::query()
-> where...
->get();
}
And maybe in the future I want to display those who have externalLinks, I shouldn't calculate them after I fetch them in a paginated page.
Or in another example I have a users table and to calculate overdraw, debt amount I have to do some calculations, so it causes N+1 query problem, or again, maybe I want to display those who are in debt.
How to solve these kinds problems?
Please or to participate in this conversation.