简体   繁体   中英

Laravel 5 orderby one-to-one relation

I have a very basic problem using Laravel 5.1 and Eloquent.

For the sake of simplicity, i've reduced my issue with this example : I have 2 models :

Leads:

ID  |  name  |  fk_city

Cities:

ID  |  name  |  postalcode

In Leads.php model :

public function city() {
    return $this->belongsTo('\App\Models\Cities','fk_city');
}

I would like to sort the leads on the city's name.

I've tried the eagger load orderby :

Leads::with(['city'=>function($q) {
    $q->orderby('name','desc');
}])->get();

But it doesn't affect the results.

I've also read that we must use the "join()" statement and manually tells Eloquent what to do. It seems overkill as this kind of sort is a really basic stuff that any ORM must be natively able to do.

Thank you for your ideas :)

Eloquent follows Active record pattern so usually does the eager loading using separate queries. You will need join for this:

Leads::join('cities', 'leads.fk_city', '=', 'cities.ID')->orderby('cities.name','desc')->with('city')->get();

If you are going to need this kind of query often you can create an scope in your model to reuse the query.

Other option is, since your results are a Laravel Collection, you can use the methods sortBy() or sortByDesc() of the collection object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM