简体   繁体   English

在Laravel中获得最大金额的价值

[英]Get value with max amount in Laravel

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). 我正在使用laravel-page-view-counter来计数我的产品的访问量,并且效果很好,我需要做的是按访问量获得前10个产品的列表(获取访问量最大的10个产品) 。

Here is what I have: 这是我所拥有的:

$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']);
});

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). 但是它从最低的产品访问返回到最高的访问(显示0访问的产品直到100访问的产品)我需要显示的反向方法(首先访问100的产品)。

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();

I hope you will understand. 希望您能理解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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