2016-11-04 53 views
1

我有問題來計算​​不爲空的設備數。從其他表中計數

它需要通過用戶user_id獲取所有商店,然後計算所有​​不爲空的設備。

$shops = Shop::with('devices')->where('user_id', $userId)->get(); 

$deviceActive = $shops->reduce(function ($carry, $item) { 
    return $carry + $item->devices->whereNotNull('guid')->count(); 
}); 

dd($deviceActive); 

它工作時,我做的:

return $carry + $item->devices->count(); 

,但它需要計算其中​​不爲空。

我也有興趣聽聽是否有替代reduce的方法。

回答

1

由於$item->devices是一個集合,沒有集合的whereNotNull()。因此,嘗試使用where()

$item->devices->where('guid', '<>', null)->count(); 
0

嘗試:

$shops = Shop::with('devices') 
->where('user_id', $userId) 
->where('guid', '!=', null)->get(); 

$get_count = count($shops); // it return how many values have $shops 

OR

$shops= DB::table('devices')->where('user_id', $userId) 
    ->where('guid', '!=', null)->get(); 

$get_count = count($shops); 

,如果你沒有足夠的類DB添加在您的控制器:

use DB; 
+0

那將返回數量的商店,而不是設備。 –