如何对有序的"有很多"关系进行分页?

Sau*_*lva 6 laravel laravel-5 laravel-5.1

我想分页以下关系(一个包含许多应用的类别):

class Category extends Model
{
    public function apps()
    {
        return $this->hasMany('App\App')->orderBy('current_price', 'asc');
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是,当我添加->paginate(10);到该行的末尾时,我收到以下错误:

关系方法必须返回Illuminate\Database\Eloquent\Relations\Relation类型的对象

我在这里错过了什么?

Tho*_*Kim 14

你试过这个吗?

$category = Category::first();
$apps = $category->apps()->paginate(10);
return view('example', compact('category', 'apps'));
Run Code Online (Sandbox Code Playgroud)

然后,在您的视图中,您可以循环浏览应用程序.

@foreach ($apps as $app)
    {{ $app->id }}
@endforeach

{!! $apps->render() !!}
Run Code Online (Sandbox Code Playgroud)

如果要将其设置为与类别的关系,可以使用以下setRelation方法:

$category = Category::first();
$category->setRelation('apps', $category->apps()->paginate(10));
return view('example', compact('category');
Run Code Online (Sandbox Code Playgroud)

然后在你看来:

@foreach ($category->apps as $app)
    {{ $app->id }}
@endforeach

{!! $category->apps->render() !!}
Run Code Online (Sandbox Code Playgroud)