V
V
Voll.2018-02-13 00:39:27
Laravel
Voll., 2018-02-13 00:39:27

Is it possible to sort by Relation in Eloquent?

There is an entity that pulls other entities: User::with('withdrawals.withdrawalitems')->get(); Is it possible to use eloquenta methods (without losing access to models) to sort (or manipulate) by withdrawalItems?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alex Wells, 2018-02-13
@Alex_Wells

Yes. whereHas.

V
Victor, 2018-02-13
@v_decadence

Sorting by relation field only via manual JOIN, since with is performed by a separate query.
Something like:

$query = Post::join('categories', 'categories.id','=','products.category_id');
$query = $query->select('categories.name as cat_name','products.*');
$query = $query->orderBy('cat_name','asc');
$records = $query->get();

A
anlamas, 2018-02-15
@anlamas

Pagination won't work for relationships. Only for the main entity, in your case for User.
And for sorting

User::with(['withdrawals' => function($query) {
    $query->select('id', 'name')->orderBy('created_at')->with(['withdrawalitems' => function($query) {
        $query->select('id', 'name')->orderByDesc('created_at')
    }])
}])->get();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question