Laravel Orderby Relationship Count

Laravel OrderBy relationship count

Edit: If using Laravel 5.2 or greater, use kJamesy's answer. It will likely perform a bit better because it's not going to need to load up all the participants and hackathons into memory, just the paginated hackathons and the count of participants for those hackathons.

You should be able to use the Collection's sortBy() and count() methods to do this fairly easily.

$hackathons = Hackathon::with('participants')->get()->sortBy(function($hackathon)
{
return $hackathon->participants->count();
});

Laravel OrderBy Relationship count with pagination

Finally found a good solution for the problem:

$products = $products->join('orders', function ($join) {
$join->on('orders.product_id', '=', 'products.id')
->where('orders.status', '=', 2);
})
->groupBy('products.id')
->orderBy('count', $order)
->select((['products.*', DB::raw('COUNT(orders.product_id) as count')]))->paginate(50);

Count and order by relation with Laravel and Eloquent

You can use withCount to retrieve relation count and order it with orderBy(*_count). Something like,

Post::withCount('comments')->orderBy('comments_count', 'desc')->get()


Related Topics



Leave a reply



Submit