Don't try to load everything at once. First get all the papers. After that eager load their authors and pages.
$keywords = ['user` input value','another user input value'];
$papers = getPapers($keywords);
...
function getPapers(array $keywords) {
return Paper::whereHas('tags', function ($query) use ($keywords) {
$query->whereIn('name', $keywords);
}, '=', count($keywords))
->orderByDesc('created_at')
->with(['author', 'pages'])
->get();
}
I think this will be reaaaaaly slow. You might try it the other way around.
// Fetch tags first and eager load their papers
$tags = Tag::whereIn('name', $keywords)->with('papers')->get();
// Intersect the papers of all tags
$papers = $tags->skip(1)->reduce(function($papers, $tag) {
return $papers->intersect($tag->papers);
}, $tags->first()->papers);
$papers->load('author', 'pages');
Index the 'name' column in the tags table to make the first query fast enough. A unique index is appropriate.
Also fetching all papers and then intersecting them is no good, not sure how to do that in the database itself. The least thing to avoid it is to have a PivotModel and intersect those.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community