Laravel中的分页和渴望加载

时间:2014-09-09 12:15:34

标签: laravel pagination eager-loading

My Controller method is:

$topics=Topic::with(array('subtopics'=>function($query){
            $query->orderBy('glc_subtopic_priority','asc');
        }))->with('subtopics.resources')->find($id)->paginate(1);
        return View::make('subtopics.index')->with('topics', $topics);

我渴望加载它,它工作正常。但是现在我想对此进行分页。我试过了 {{ dd($topics->toArray()) }}并且它返回给我:

array (size=7)
  'total' => int 2
  'per_page' => int 1
  'current_page' => int 1
  'last_page' => int 2
  'from' => int 1
  'to' => int 1
  'data' => 
    array (size=1)
      0 => 
        array (size=5)
          'id' => int 1
...........

问题出在我显示数据时。我正在使用

@foreach($topics->subtopics as $topic)
    <li>{{ $topics->glc_subtopic_name }}</li>
        {{ $topic->glc_subtopic_content }}
        @foreach($topic->resources as $resource)
        <br/>{{ $resource->glc_subtopic_resource_url }}
    @endforeach
@endforeach

这会返回错误: Undefined property: Illuminate\Pagination\Paginator::$subtopics

如何访问分页变量$topics中的数据。

1 个答案:

答案 0 :(得分:0)

如果您需要为subtopics指定查询,则应该从该查询中急切加载resources模型,而不是再次加载subtopics

试试这个:

$topics = Topic::with(['subtopics' => function($query){
    $query->with('resources')->orderBy('glc_subtopic_priority','asc');
}])->find($id)->paginate(1);

return View::make('subtopics.index', ['topics' => $topics]);