Support the ongoing development of Laravel.io →
Eloquent Laravel
Last updated 2 years ago.
0

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();
}
Last updated 4 years ago.
0

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.

0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.