I am using this for my api when i visit someone profile:
return response()->
json(
User::load(["posts.comments"])
->where('username', request('username'))
->firstOrFail()
);
Now when I want to use paginate on relation I do it like this:
$user->posts()->paginate(10);
But I need relation so I found:
$user->setRelation('posts', $user->posts()->paginate(10));
Now I am wondering is there a way to create custom relation method inside model so when I use load(['posts.comments'])
it returns that custom relations?
One way is to do this:
return response()->
json(
User::with(['posts' => function($q) {
$q->paginate(5);
}, 'posts.comments' => function($q) {
$q->paginate(5, ['*'], 'commentsPage', request('commentsPage'));
}])
->where('username', request('username'))
->firstOrFail()
);
Although I am not sure how to pass $q->nextPageUrl()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.