你能用Laravel对嵌套查询进行分页吗?

时间:2015-07-14 17:18:52

标签: php laravel laravel-5

是否可以对此嵌套查询进行分页?

user.php的

public function favoritePosts()
{
    return $this->morphedByMany('App\Post', 'favoritable', 'favorites')
                ->withTimestamps();
}

ProfilesController.php

public function posts($username)
{
    $user = User::with(['profile', 'favoritePosts' => function($q){
        $q->paginate(15);
    }])->whereUsername($username)->firstOrFail();
    return view('profiles.posts')->withUser($user);
}

简档/ posts.blade.php

...
{!! $user->favoritePosts->appends(Request::except('page'))->render() !!}
...

错误

Call to undefined method Illuminate\Database\Eloquent\Collection::appends()

1 个答案:

答案 0 :(得分:0)

我最终使用了两个查询。

public function posts($username)
{
    $user = User::with('profile')->whereUsername($username)->firstOrFail();
    $posts =  $user->favoritePosts()->paginate(15);
    return view('profiles.posts')->withUser($user)->with(compact('posts'));
}