2016-11-04 89 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

那将返回数量的商店,而不是设备。 –