调用未定义的方法 Illuminate\Database\Eloquent\Builder::sortByDesc()

kya*_*kya 7 laravel eloquent

我正在尝试获取 5 个最近项目的列表,并根据created_at 日期字段按降序对它们进行排序。我使用 Model::with() 来避免 n+1 问题。下面是代码:

  $recentProjects = Project::with('visits','team')
                                ->whereYear('created_at',now()->year)
                                ->sortByDesc('created_at')->take(5)
                                ->get();
Run Code Online (Sandbox Code Playgroud)

但是,我收到错误:

调用未定义的方法 Illuminate\Database\Eloquent\Builder::sortByDesc()

我尝试了不同的方法,比如Project::orderBy()跟着一起,但也没有锻炼。

sta*_*sta 11

sortByDesc方法按属于模型中某种雄辩关系的字段对集合进行排序。

如果您尝试使用sortByDesc模型本身(您当前的模型对象)对集合进行排序,请使用orderBy而不是sortByDesc

Project::orderBy('created_at', 'DESC')
    ->with('visits','team')
    ->whereYear('created_at', now()->year)
    ->take(5)
    ->get();
Run Code Online (Sandbox Code Playgroud)