在Laravel中获得最大金额的价值 [英] Get value with max amount in Laravel
本文介绍了在Laravel中获得最大金额的价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 laravel-page-view-counter 进行计数访问我的产品,并且效果很好,我需要做的是按访问量获得前10名产品的列表(获取访问量最大的10种产品).
I'm using laravel-page-view-counter to count visits of my products and it's working just fine, what i need to do is to get list of top 10 products by their visits (get 10 products which has largest number of visits).
这就是我所拥有的:
$visits = Product::join('page-visits', function ($join) {
$join->on('products.id', '=', 'page-visits.visitable_id');
})->get();
$sorted = $visits->sortBy(function ($product, $key) {
return count($product['visits']);
});
但是它从最低的访问量返回到最高的访问量(显示访问量为0的产品,直到访问量为100的产品),我需要用相反的方法来显示(访问量最高的100的产品).
But It return from lowest product visits to highest one (it shows product with 0 visit till product with 100 visits) I need reverse method of that to show (product with 100 visits first).
推荐答案
您可以使用查询生成器和类似以下的原始查询轻松完成此操作:
You can do it easily with query builder and some raw queries like this:
$visits = DB::table('products')
->join('page-visits','products.id','=','page-visits.visitable_id')
->select(DB::raw('count(visitable_id) as count'),'products.*')
->groupBy('id')
->orderBy('count','desc')
->take(10)
->get();
希望您能理解.
这篇关于在Laravel中获得最大金额的价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文