【问题标题】:Join and OrderBy within with laravel eloquent query使用 laravel 雄辩的查询加入和 OrderBy
【发布时间】:2020-05-16 05:50:42
【问题描述】:

我想显示一个品牌的基于城市的有序商店列表。

这是我试过的代码

 $brand = Brand::where('slug','=',$slugurl)
      ->with(['stores' => function($q){
        $q->where('status', 1)
        ->join('cities', function ($join){
              $join->on('cities.id', '=', 'stores.city_id')->orderBy('cities.sort_number', 'DESC');
        });

      }])
      ->firstOrFail();

表的关系:

品牌有很多店铺,店铺属于城市

列表结果输出未根据城市 sort_number 排序。知道如何实现吗?

【问题讨论】:

    标签: mysql laravel laravel-5 join eloquent


    【解决方案1】:

    orderjoin的闭包里没用。

    您需要在join 之后附加orderBy

    $brand = Brand::where('slug','=',$slugurl)
          ->with(['stores' => function($q){
            $q->where('status', 1)
              ->join('cities', 'cities.id', '=', 'stores.city_id')
              ->orderBy('cities.sort_number', 'DESC');
          }])
          ->firstOrFail();
    

    这个查询转换为原始 sql 是:

    select * from brands where slug = ? limit 1;
    
    select * from stores 
    join cities on cities.id = stores.city_id 
    where status = 1 and stores.brand_id in (?)
    order by cities.sort_number desc;
    

    【讨论】:

    • 结果顺序还是一样,没有有序的店铺列表
    • @TomKur 我已经试过了,它有效,你可以发布未排序的结果
    • 当我在我的模型中加入并订购时它可以工作
    • @TomKur 我想你可以使用DB::getQueryLog()。它将帮助您输出原始 sql,您会发现order by 是否存在
    猜你喜欢
    • 2018-05-12
    • 1970-01-01
    • 2018-01-26
    • 2021-07-23
    • 1970-01-01
    • 2017-11-11
    • 2023-04-05
    • 1970-01-01
    相关资源
    最近更新 更多