Laravel 5.3将查询构建器转换为LengthAwarePaginator

时间:2016-10-19 09:59:37

标签: laravel

我需要使用switch case为我需要运行的查询添加约束。我需要它与分页一起工作,我试过这个:

restoring users from /home/mongod/admin/system.users.bson   
error: Writes to config servers must have batch size of 1, found 11

我得到了

$albums = Album::with(array(
                'images' => function ($query) {
                    $query->orderBy('order', 'asc');
                }
            ))
            ->where('votes.votable_type','App\Models\Album')
            ->groupBy('albums.id');
            $albums->published()->orderBy('created_at', 'desc')->paginate(30);
            dd($albums);

如果我跑

Builder {#361 ▼
  #query: Builder {#350 ▶}
  #model: Album {#351 ▶}
  #eagerLoad: array:2 [▶]
  #macros: array:5 [▶]
  #onDelete: Closure {#364 ▶}
  #passthru: array:11 [▶]
  #scopes: array:1 [▶]
  #removedScopes: []
}

我得到了

$albums = Album::with(array(
                'images' => function ($query) {
                    $query->orderBy('order', 'asc');
                }
            ))
            ->where('votes.votable_type','App\Models\Album')
            ->groupBy('albums.id')
            ->published()->orderBy('created_at', 'desc')->paginate(30);
            dd($albums);

为什么这两种方法有区别?我需要使用第一种方法来使用switch case添加约束,我不能使用第二种方法。但是第一种方法我没有得到LengthAwarePaginator,如何修复它以便我得到它?

1 个答案:

答案 0 :(得分:2)

如果您希望将变量$ albums保存到此变量,则应重新声明该变量。改变这个:

$albums->published()->orderBy('created_at', 'desc')->paginate(30);

要:

$albums = $albums->published()->orderBy('created_at', 'desc')->paginate(30);