Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel / Eloquent order Relationship Descending without Raw SQL?

Is it possible to order by a relationship, so that the records in that relationship are discending without using raw SQL?

Example:

$device = CustomerDevice::with('user')->with('customerDeviceHistory')->find($did);

Entries in customerDeviceHistory should be descending.

like image 268
xTheWolf Avatar asked Dec 21 '25 16:12

xTheWolf


2 Answers

This will order by id in desc order of customerDeviceHistory id.

$device = CustomerDevice::with('user')->with(['customerDeviceHistory'=>function($query)
    {
        $query->orderBy('id','desc');
    }
])->find($did);
like image 56
Sanzeeb Aryal Avatar answered Dec 24 '25 05:12

Sanzeeb Aryal


maybe, for example:

function customerDeviceHistory() {
   return $this->hasOne('App\[DeviceHistory]', 'id', 'deviceHistory_id')->orderBy('date', 'desc');
}

Add orderBy to relationship function

like image 38
Ilya Yaremchuk Avatar answered Dec 24 '25 07:12

Ilya Yaremchuk