Ad

Laravel OrderBy In Relationship Data

How to order in relationship collection for the output grocery.name? It just sorts by the parent ID as default now, which I'm not interested in.

I have tried to change this controller...

This how it looked like

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

AND this is my changes, were I want to change the grocery.name to output it alphabetically

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

My Output were it looks like it order is by the 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"
}
}
]

My table structure

Groceries
- id
- name
- measurement

Relation in Model

class DailyList extends Model
{


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

Answer

You are only ordering the groceries. To order your daily lists, you will need to make some SQL code to fix it.

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

You include the grocery item if it has one with the left join. Then you have that row including in your data, you can then order by the groceries. To avoid messing with the Laravel ORM mappings, only select groceries.

Ad
source: stackoverflow.com
Ad