【问题标题】:Laravel OrderBy in relationship data关系数据中的 Laravel OrderBy
【发布时间】:2020-07-08 01:33:42
【问题描述】:

如何在关系集合中为输出grocery.name 排序?它现在只是按父 ID 排序为默认值,我对此不感兴趣。

我已尝试更改此控制器...

原来是这样的

public function indexalpha()
    {
        $list = DailyList::with('grocery')->where('completed', 0)->get();
        return $list;
    }

这是我的更改,我想更改grocery.name 以按字母顺序输出

public function indexalpha()
    {
        $list = DailyList::with(['grocery' => function ($q) {
            $q->orderBy('name', 'desc');
        }])->where('completed', 0)->get();
        return $list;
    }

我的输出看起来像是按 id 排序的

[
{
"id": 554, // this is apparently the default sorting
"grocery_id": 110,
"amount": 1,
"completed": 0,
"created_at": "2020-03-27 08:29:53",
"updated_at": "2020-03-27 08:29:53",
"grocery": {
  "id": 110,
  "name": "Cookie", // Want to order this part!!!
  "measurement": "Stk",
  "created_at": "2020-02-20 12:25:26",
  "updated_at": "2020-02-20 12:25:26"
}
},
{
"id": 555, // this is apparently the default sorting
"grocery_id": 107,
"amount": 1,
"completed": 0,
"created_at": "2020-03-27 08:51:10",
"updated_at": "2020-03-27 08:51:10",
"grocery": {
  "id": 107,
  "name": "Pampers", // Want to order this part!!!
  "measurement": "Stk",
  "created_at": "2020-01-27 13:50:24",
  "updated_at": "2020-01-27 13:50:24"
}
}
]

我的表结构

Groceries
- id
- name
- measurement

模型中的关系

class DailyList extends Model
{


    public function grocery()
    {
        return $this->belongsTo(Grocery::class);
    }
}

【问题讨论】:

    标签: laravel sorting controller relationship


    【解决方案1】:

    您只是订购杂货。要订购您的每日清单,您需要编写一些SQL 代码来修复它。

    DailyList::leftJoin('groceries', 'daily_lists.grocery_id', 'groceries.id')
        ->orderBy('groceries.name')
        ->with('grocery')
        ->where('completed', 0)
        ->select('groceries.*')
        ->get();
    

    如果杂货项目具有左连接,则包括该项目。然后,您的数据中包含该行,然后您可以按杂货订购。为避免弄乱Laravel ORM 映射,请仅选择杂货。

    【讨论】:

      【解决方案2】:

      从 laravel 6 起,你可以用更简洁的语法做到这一点

      https://laravel-news.com/eloquent-subquery-enhancements

      $list = DailyList::with('grocery')->orderByDesc(
          ProductPrice::select('name')
              ->whereColumn('daily_lists.grocery_id', 'groceries.id')
              ->orderByDesc('name')
              ->limit(1)
      )->where('completed', 0)->get();
      

      【讨论】:

        猜你喜欢
        • 2014-08-04
        • 2013-08-11
        • 1970-01-01
        • 2019-05-14
        • 1970-01-01
        • 2020-03-25
        • 2018-06-06
        • 1970-01-01
        • 2015-11-21
        相关资源
        最近更新 更多