0

I have a model that I want to sort based on a relationship property.

  1. First model "DeviceType":
public function make()
{
    return $this->hasMany(DeviceMake::class);
}
  1. Second model: "DeviceMake":
public function type()
{
    return $this->hasOne(DeviceType::class, 'id', 'device_type_id');
}

public function model()
{
    return $this->hasMany(DeviceModel::class);
}
  1. Controller:
$type = DeviceType::with(['make'])->where('id', '=', $device_type_id)->first();
  1. Table name is device_makes and I want to sort it by name. How can I do this?
Mesut Akcan
  • 899
  • 7
  • 19
ip93
  • 1
  • 3
  • u can try this `$type = DeviceType::with(['make'])->where('id', '=', $device_type_id)->orderBy('name', 'desc')->first();` – latenight Mar 08 '20 at 16:09
  • @CamBoKiDz not working :( – ip93 Mar 08 '20 at 16:29
  • Your relationship models should be plural if they return a relationship that could contain more than one item. `public function models()`, `public function makes()`, etc. – miken32 Mar 08 '20 at 22:28
  • 1
    Does this answer your question? [Laravel Eloquent: How to order results of related models?](https://stackoverflow.com/questions/25700529/laravel-eloquent-how-to-order-results-of-related-models) – miken32 Mar 08 '20 at 22:30
  • @miken32 no, It's not the answer – ip93 Mar 09 '20 at 15:35

1 Answers1

0

And what about?

$type = DeviceType::with(['make' => function ($query) { 
    $query->orderBy('name', 'asc');
}])->where('id', '=', $device_type_id)->first();

Please note that first() will only return the first model that matches your query whereas get() will return all of them.

Maybe you could try this instead in your Model:

public function make() { 
    return $this->hasMany(DeviceMake::class)->orderBy('name', 'asc'); 
} 
P0rt4rd
  • 46
  • 2