Laravel查询-获取最畅销的商品
我对Laravel是新手,我使用Laravel 5.1 我在数据库中有这个表:Laravel查询-获取最畅销的商品,laravel,eloquent,sum,max,Laravel,Eloquent,Sum,Max,我对Laravel是新手,我使用Laravel 5.1 我在数据库中有这个表: 这是购买itesm的表格。我想知道计算最畅销凭证的最佳方法是什么-每次购买都有凭证id…如果您想使用雄辩的 $Voucher = Sales::sortBy(function ($sale) { return $sale->voucher_id->count(); }, SORT_REGULAR, true)->take(1)->get(); 最好的方法是使用一个查
这是购买itesm的表格。我想知道计算最畅销凭证的最佳方法是什么-每次购买都有凭证id…如果您想使用雄辩的
$Voucher = Sales::sortBy(function ($sale) {
return $sale->voucher_id->count();
}, SORT_REGULAR, true)->take(1)->get();
最好的方法是使用一个查询进行计数,并在同一查询中获取畅销书的id:
PurchasedItem::select(DB::raw('COUNT(id) as cnt', 'voucher_id'))->groupBy('voucher_id')->orderBy('cnt', 'DESC')->first();
我将尝试并成功完成这段代码。你可以尽最大努力
<?php
$topsales = DB::table('purchase_order_details')
->leftJoin('products','products.id','=','purchase_order_details.product_id')
->select('products.id','products.name','purchase_order_details.product_id',
DB::raw('SUM(purchase_order_details.quantity) as total'))
->groupBy('products.id','purchase_order_details.product_id','products.name')
->orderBy('total','desc')
->limit(6)
->get();
?>
I write:$thebest=Auth::user()->sales()->sortBy(函数($sale){return$sale->凭证id->count();},SORT_REGULAR,true)->take(1);但是get:调用undefined方法illumb\Database\Query\Builder::sortBy()如何使用$thebest=Auth::user()->sales()->。。。下一步是什么?尝试使用:$thebest=Auth::user()->sales()->select(DB::raw('COUNT(id)as cnt','concedure_id'))->groupBy('concedure_id')->orderBy('cnt','DESC')->first();类“App\Http\Controllers\DB”未找到您必须在文件的顶部添加:“use illumb\Support\Facades\DB;”。ok可以工作,但您知道如何使用雄辩的函数max()构建它吗?