简体   繁体   中英

Laravel 5.4 Eloquent SUM and ORDER BY pivot table column

I need an Eloquent query that retrieves the most purchased products in my database. The tables are products , products_purchases , purchases . Products and purchases both have a many-to-many relationship.

The pivot table products_purchases has a pivot field called quantity , which has the total quantity of a product bought on a purchase.

I tried to get the records like this:

$data['most_purchased'] = Products::whereHas('purchases', function($query){
        $query->selectRaw('SUM(products_purchases.quantity) AS qty')->orderBy('qty', 'desc')->groupBy('product_id');
})->get();

But it doesn't give accurate values, what is the right way to do this?

This code works:

Products::join('products_purchases', 'product.id','=','products_purchases.product_id')
           ->selectRaw('product.*, SUM(products_purchases.quantity) AS qty')
           ->groupBy('product.id')
           ->orderBy('qty', 'desc')
           ->get();

But, is there another "cleaner" way to do this without using join ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM