R
R
Roman Volkov2016-03-23 13:31:21
Laravel
Roman Volkov, 2016-03-23 13:31:21

How to sort by nested laravel model?

There is a "Products" model, each product belongs to 1 category. How to get categories sorted by the number of products in a category through ActiveRecord in Laravel?
$category = Category::active()->orderBy([])->->paginate($per_page);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anatoliy Lyovkin, 2016-03-24
@Alyovkin

Use the sortBy() and count() collection methods.
Example:

$categories = Category::active->with('product')->get()->sortBy(function($category)
{
    return $category->product->count();
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question