Akeno's avatar

Paginate within a pivot table

Hi,

how can I paginate data from a pivot table? I know it could work like this:

(user and blueprint have a many-to-many-relationship)

$blueprints = User::find($user->id)->blueprints()->simplePaginate(10);

But this way, it does not eagerly load the data, thus many queries are generated :/ Also, I can't specify any constraints etc. Is there a way to achieve a pagination like this:

$blueprints = User::with(['blueprints' => function($q)
        {
            $q->orderBy('name', 'asc');
            $q->with('slots');
            $q->simplePaginate(10);
        }])->find($user->id)->blueprints;

?

Thank you in advance

0 likes
4 replies
Akeno's avatar

hm, okay so it's better to have somewhat more queries than to have two queries but hundreds of results, right?

Okay, thank you :)

bestmomo's avatar

Sometimes it's better to create paginator manually.

Akeno's avatar

hm, that's another possibility.

I mean, you could have something like this in the URL:

public/blueprints?start=5

Then you set a $step variable(how much you want to have per page) and then you can do it like this:

$end = $start + $step;
$blueprints = User::with(['blueprints'] => function($q) use($start, $end)
{
        $q->limit($start, $end);
})->find($user-id)->blueprints;

The only con-argument I can think of is the following: You don't know, how many pages you have. You just can say "go to next page" and "go to previous page".

Please or to participate in this conversation.