【问题标题】:proper use of Laravel's paginate method?正确使用 Laravel 的分页方法?
【发布时间】:2018-10-17 23:52:18
【问题描述】:

当我将paginate 方法与以下语句一起使用时:

$user = User::where('id', 1)->first();
$images = $user->images->paginate(3);

我收到以下错误:

方法 Illuminate\Database\Eloquent\Collection::paginate 没有 存在

但是当我用以下语句调用它时:

$images = Image::where('user_id', $user->id)->paginate(3);

它相应地工作......我对 Laravel 还很陌生,所以请原谅我的无知,但结果差异的原因是什么?两个语句都不返回集合吗?

【问题讨论】:

  • 你用的是哪个版本?
  • 使用dd($images) 看看有什么不同。
  • $images = $user->images()->paginate(3);
  • @TruongDang 天哪。一个 Django 开发者迁移到 Laravel 的编年史。我觉得自己像一只狒狒!成功了。
  • 如果需要代码,您可以在数组上应用分页,然后请告诉我@John Durand

标签: php laravel pagination


【解决方案1】:

paginate 是查询生成器的方法,而不是集合。如果要对集合进行分页,则需要进行手动分页:

$imagesPage = new LengthAwarePaginator($user->images->forPage($page,3), $user->images->count(), 3, $page); //Where $page is the current page number

您也可以对查询生成器进行分页:

$images = $user->images()->paginate(3); 

请注意,如果您使用第二种方法,则不需要预先加载图像。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-16
    • 1970-01-01
    • 2018-08-16
    • 1970-01-01
    • 2016-10-22
    • 1970-01-01
    相关资源
    最近更新 更多