如何使用 Eloquent 中的"with"子句对结果进行排序?



我想根据with子句的第一个结果对类别进行排序。

例如,有3个类别,每个类别都包含预留:

  1. 动物:{狗,猫,马}
  2. 食物:{汉堡、牛排、沙拉}
  3. 车辆:{汽车、摩托车、自行车}

如果我的搜索查询是汽车我希望我的收藏返回:

  • 车辆
  • 食物
  • 动物

但我不知道怎么做,有人能帮我吗?

我无法更好地解释。。。

谢谢!

$search = $request->search ?? '';
$categories = Category::with(['prestations' => function($query) use($search){
$query->where('prestation', 'LIKE', '%' . $search . '%');
}])
//order by the categories with first result ?
->get();

使用单独的查询来检索冗长的关系,该查询发生在检索主模型的查询之后,因此无法根据关系查询中获得的值对主查询结果进行排序。然而,在您的特定用例中,您可以在检索结果后进行排序:

$search = $request->search ?? '';
$categories = Category::with(['prestations' => function($query) use($search){
$query->where('prestation', 'LIKE', '%' . $search . '%');
}])
->get()
->sortBy(function (Category $category) {
return $category->prestations->count(); // Or any other sort criteria you want
});

最新更新