分页渴望加载的关系结果

时间:2019-02-15 22:49:33

标签: php laravel eloquent eloquent--relationship

我正在尝试使用与此相似的代码对关系结果集进行分页

<?php

class MainController extends Controller {

    public function show(Main $main)
    {
        $main = $main->with([
            'secondaryMorph' => function ($query) {
                $query->orderBy('ocurred_at');
                $query->paginate(50);
            }
        ])->first();

        return view('main.show')->with(compact('main'));
    }
}

但是当视图的这部分代码运行时,会引发异常:

<td colspan="3">Mostrando {{ $secondary->count() }} de {{ $secondary->total() }}</td>
<td colspan="3">{{ $secondary->links() }}</td>
  

ErrorException(E_ERROR)   方法Illuminate \ Database \ Eloquent \ Collection :: total不存在。

如何在分页中使用预加载?

1 个答案:

答案 0 :(得分:0)

怎么样:

$main = $main->first();
$secondary = $main->secondaryMorph()->paginate();
return view('main.show')->with(compact('main','secondary'));

然后在Blade中:

<td colspan="3">Mostrando {{ $secondary->count() }} de {{ $secondary->total() }}</td>
<td colspan="3">{{ $secondary->links() }}</td>