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
Ternary Operator Left Associativity
PHP Hierarchical Array - Parents and Childs
How to Check If a Video Exists on Youtube, Using PHP
How to Integrate Nodejs + Socket.Io and PHP
PHP Objects VS Arrays -- Performance Comparison While Iterating
Unique and Temporary File Names in PHP
PHP Combine Two Associative Arrays into One Array
Error While Sending Query Packet
PHP Warning: Module Already Loaded in Unknown on Line 0
Removing Last Comma from a Foreach Loop
File_Get_Contents() Give Me 403 Forbidden
How to Read a .Tar.Gz File with PHP