【问题标题】:Laravel 5.2: Order Models by Pivot table fieldLaravel 5.2:按数据透视表字段排序模型
【发布时间】:2018-03-30 11:40:14
【问题描述】:

我有以下型号:

- User:
id

- Product:
id
lid
user_id

- ProductCategories:
product_id
category_id
lid

- Category:
id

关系:

用户拥有很多产品

产品属于多类别

我有一个用户,我有一个类别 id,我需要属于该类别的产品,按盖子从 ProductCategory 订购

什么是最好的解决方案?

目前这是我正在尝试使用的,但它没有以正确的方式排序:

$products = $user->products()->whereHas('categories', function($q) use ($category){
    $q->where('category_id', $category)->orderBy('product_categories.lid', 'asc');
})->paginate(20);

【问题讨论】:

    标签: php mysql model eloquent laravel-5.2


    【解决方案1】:

    解决办法是:

    $products = $user->products()->whereHas('categories', function($q) use ($category){
        $q->orderBy('product_categories.lid', 'asc');
    })
    ->leftJoin('product_categories', 'products.id', '=', 'product_categories.product_id')
    ->leftJoin('categories', 'product_categories.category_id', '=', 'categories.id')
    ->where('product_categories.category_id', $category)
    ->select('products.*')
    ->orderBy('product_categories.lid', 'asc')->paginate(20);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-06
      • 1970-01-01
      • 1970-01-01
      • 2021-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多