2016-05-12 19 views
1

我的主要目的是展示我最暢銷的產品。Laravel 5.1 - mysql orderby計數截然不同的最高值

我的表名是order_item的列(ID,cart_id,PRODUCT_ID,等等。)

控制器:

$orderitems = DB::table('order_items') 
     ->select('product_id')->get(); 

HTML:

<div id="menu2" class="tab-pane fade"> 
    @foreach($orderitems as $order) 
     {{$order->product_id}}<br> 
    @endforeach 
</div> 

本的foreach操作的結果是:2,6,2,4,6,6.

我的目的是顯示結果:6,2,4。 (我們有三個6,所以它可能是第一個,兩個2它可能是第二個,一個4它可能是最後一個) 我想要以這個順序先顯示最高計數的分號數。

我在我的控制器tryed代碼:

$orderitems = DB::table('order_items') 
     ->select('product_id')->orderBy(distict(count('product_id'))); 

但它失敗,提示信息:

Fatal error: Call to undefined function App\Http\Controllers\distict() 

回答

1

在這裏,你應該如何使用distinct方法(和orderBy):

$orderitems = DB::table(DB::raw('(SELECT product_id, COUNT(*) as product_count FROM order_items GROUP BY product_id) AS subquery')) 
    ->select('product_id') 
    ->orderBy('product_count') 
    ->get(); 
+0

我有一個錯誤: In有效的參數爲foreach()(視圖:C:\ wamp64 \ www \ test3 \ resources \ views \ master \ master.blade.php) –

+0

我的不好...我只是重新編輯我的答案。我忘了重載' - > get()' –

+0

另一個錯誤: 致命錯誤:調用數組 –