【问题标题】:Laravel: paginate collection issueLaravel:分页收集问题
【发布时间】:2018-05-09 09:17:44
【问题描述】:

这是我的代码:

模型:

public static function myWishlist(){
    $id = Auth::id();
    $book_id = Wishlist::where('user_id', $id)->pluck('book_id');
    return DB::table('books')->whereIn('id', $book_id)->get();

控制器:

public function index(Request $request)
{$books = Wishlist::myWishlist()->paginate(20);
return view('wishlistCRUD.index', compact('books'))
       ->with('i', ($request->input('page', 1) - 1) * 5);

但它没有向我展示所有指定的书籍,而是说:

方法分页不存在。

我也在模型中试过这个:

$book_id = Wishlist::where('user_id', $id)->pluck('book_id');
    return Book::whereIn('id',$book_id)->get();

但是它返回一个集合,我不知道如何在我的视图中显示它。

【问题讨论】:

  • paginate() 应该是查询上的方法,而不是结果集上的方法
  • 代替return DB::table('books')->whereIn('id', $book_id)->get() 使用return DB::table('books')->whereIn('id', $book_id)->paginate(20)
  • 您已经在->get() myWishlist(), paginate() 处理查询。你有一个结果。

标签: php database laravel


【解决方案1】:

得到结果后不能使用分页。

你可以这样做:

public static function myWishlist() {
    $id = Auth::id();
    $book_id = Wishlist::where('user_id', $id)->pluck('book_id');
    return Book::whereIn('id', $book_id);
}

public function index(Request $request) {
    $books = Wishlist::myWishlist()->paginate(20);
    return view('wishlistCRUD.index', compact('books'))
       ->with('i', ($request->input('page', 1) - 1) * 5);
}

【讨论】:

  • 谢谢,但后来我收到一个错误:缺少 Illuminate\Support\Collection::get() 的参数 1,在 /var/www/html/bachelor_thesis/vendor/laravel/framework/ 中调用src/Illuminate/Pagination/AbstractPaginator.php 在第 577 行并定义
  • 请检查更新的答案,您不需要使用 get 与分页。
  • 它就是这样工作的!非常感谢您,祝您有愉快的一天!
【解决方案2】:

首先不需要使用static functioneloquent already does that

其次,您可以像这样使用local scopes

型号:

public function scopeUserWishlist($query, $userID)
{
    // Although a join would be nicer !
    $book_ids = Wishlist::where('user_id', $userID)
                         ->pluck('book_id');
    return $query->whereIn('id', $book_ids);
}

控制器:

public function index(Request $request)
{
    $books = Wishlist::userWishlist(Auth::id())
                     ->paginate(20);
    return view('wishlistCRUD.index')
       ->with('books', $books)
       ->with('i', ($request->input('page', 1) - 1) * 5);
}

【讨论】:

  • 谢谢拉米赫里拉!祝你有美好的一天!
猜你喜欢
  • 2019-12-02
  • 2017-11-22
  • 2018-09-09
  • 2021-05-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-26
  • 2019-08-29
相关资源
最近更新 更多