简体   繁体   中英

Eloquent order relationship results

I have a simple eloquent query and want to include another table with my results, however, the order of relationship results is incorrect.

Is it possible to order the results without using an SQLRAW statement

$groups = AttributeGroup::with('attribute')->where('page_id', $page->id)->get();

What I would like -

$groups = AttributeGroup::with('attribute')->orderBy('iteration', 'DESC')->where('page_id', $page->id)->get();

I get the error of Unknown column because this column is part of relationship table.

This will order each attribute relation of every attribute group result:

$groups = AttributeGroup::with(['attribute' => function ($query) {
    $query->orderBy('iteration', 'DESC');
}])->where('page_id', $page->id)->get();

Is this what you want to achieve?

You can use closures to change the query when using with and has .

$groups = AttributeGroup::with(['attribute' => function($query){
    $query->orderBy('iteration');
})->where('page_id', $page->id)->get();

Details are available on https://laravel.com/docs/5.6/eloquent-relationships#constraining-eager-loads

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