Laravel OrderBy Number of paginated relationships

I have many projects, and each has many orders, some completed, some not.

I want to order them by the number of completed orders as follows:

$products = $products->orderBy(function($product) {
    return $product->orders->where('status', 2)->count();
})->paginate(15);

I know that calling an order does not work like this, but this is the best that showed the problem. SortBy does not work because I want to use pagination.

+4
source share
3 answers

Finally, I found a good solution to 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);
+5
source

Try it if it works:

    $categories = Prodcuts::with(array('orders' => function($query) {
       $query->select(DB::raw('SELECT * count(status) WHERE status = 2 as count'))
        $query->orderBy('MAX(count)')
     }))->paginate(15);

    return View::make('products.index', compact('categories'));

Note: This is not verified.

0
source

5.2 withCount .

$products = $products->withCount(['orders' => function ($query) {
    $query->where('status', 2);
}]);

: https://laravel.com/docs/5.2/eloquent-relationships

0

All Articles