【问题标题】:How can I order my results with "with" clause in Eloquent?如何在 Eloquent 中使用“with”子句对结果进行排序?
【发布时间】:2021-07-21 20:35:17
【问题描述】:

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

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

  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();

【问题讨论】:

    标签: php laravel eloquent eloquent-relationship


    【解决方案1】:

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

    $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
    });
    
    

    【讨论】:

    • 效果很好,我只是将“sortBy”更改为“SortByDesc”,因为它首先具有想要的值,谢谢!
    猜你喜欢
    • 1970-01-01
    • 2018-02-10
    • 1970-01-01
    • 1970-01-01
    • 2013-08-12
    • 1970-01-01
    • 2012-04-30
    • 2019-07-17
    • 2012-08-16
    相关资源
    最近更新 更多