【问题标题】:How to filter laravel collection如何过滤 laravel 集合
【发布时间】:2018-04-16 01:01:23
【问题描述】:

我正在尝试在 laravel 中制作过滤器。以下过滤器有效

$posts= Post::where('category',$request->category)->orderBy('id','desc')->paginate(10);

但是当我尝试做这样的事情时

public function index(Request $request)
{
    $posts= Post::where('category',$request->category)->get();
    $posts->latest()->paginate(10);
    dd($posts);

它不起作用。有人可以解释为什么会这样,并为我提供有效的代码。我的项目有多个过滤器。

错误

【问题讨论】:

  • 这是什么 laravel 版本?以及“它不起作用”是什么意思,即您看到了什么错误?
  • 这是 laravel 5.5,我的意思是较低的代码不起作用
  • 你遇到了什么错误?
  • $blogs = Blog::where('category',$request->category)->get(); $blogs->latest()->分页(10); dd($博客);这段代码给我 if (!static::hasMacro($method)) { throw new BadMethodCallException("Method {$method} 不存在。"); } 和 Method latest not found
  • 当你运行第二个代码时,你得到了什么错误。您可以使用您遇到的错误更新您的问题。这样可以避免您得到随机或猜测的问题答案。

标签: php laravel collections filter eloquent


【解决方案1】:

因为$posts = Post::all();已经执行了一个查询。

Post::where('category',$request->category)->latest()->paginate(10)->get();

会是你想要的。

注意:latest 需要 created_at

【讨论】:

    【解决方案2】:

    你该走了

    $posts = Post::where('category',$request->category)->latest()->paginate(10);
    

    get 请求是不必要的,因为分页将执行查询。

    【讨论】:

    • 如果 $request->category==null
    • 当 categoy 为空时你想发生什么?
    【解决方案3】:

    第一个通过分页进行查询,即每个构造页面获取 10 条记录

    对于第二个,根据观察,您很可能遇到了至少 2 个错误: 第一个,在使用get 方法的行上,因为该方法至少需要一个参数。

    Type error: Too few arguments to function Illuminate\Support\Collection::get()
    

    另一个因为它是一个集合,并且由于集合上没有像 paginatelatest 这样的方法,因此会引发其他错误。您应该查看 Collection 的Available methods 以了解收集所允许的方法。

    最好的解决方案之一是在进行查询时简单地对结果进行排序:

    Blog::where('category',$request->category)
        ->orderBy('created_at', 'desc') //you may use also 'updated_at' also depends on your need
        ->paginate(10);
    

    这样你就可以在分页中获得最新的信息,并且不用担心paginating a collection

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-07
      • 1970-01-01
      • 1970-01-01
      • 2021-03-02
      • 1970-01-01
      • 2017-08-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多