Laravel 5.8 查询范围

Laravel 5.8 query scope

我正在学习 laravel,我在使用查询范围时遇到了这个问题,我的代码 returns 零数据。数据库有数据。 这有点令人困惑,因为我认为我已经按照教程做对了所有事情

范围:

public static function scopeLatest($query)
{
    return $query->orderBy('id', 'asc')->get();
}

控制器:

public function index()
{
    $posts = Post::Latest();

    return view('posts.index', compact('posts'));
}

AFAIK,您将无法使用 scopeLatest,因为 Laravel 在其查询构建器上已经有一个 latest() 方法。


至于您尝试制作的范围,这里有一些提示:

  • a scope 不应定义为 static 方法
  • 你实际上不应该在你的范围内调用 get()
  • 您不需要 return 来自范围。

因此,即使这个范围实际上不会起作用(因为名称),作为示例,根据您的问题,它看起来应该是这样的:

public function scopeLatest($query)
{
    $query->orderBy('id', 'desc'); //desc should put the latest first
}

你的控制器方法(在任何一种情况下)应该是:

public function index()
{
    $posts = Post::latest()->get();

    return view('posts.index', compact('posts'));
}