2016-11-04 4 views
1

​​がnullでないデバイスの数をカウントするのに問題があります。他のテーブルからのカウント

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

をしかし​​がnullでない場合、それはカウントする必要があります。

代替方法がある場合は、私も聞きたいと思いますreduce

答えて

1

$item->devicesはコレクションであるため、コレクションにはwhereNotNull()がありません。あなたはDBがあなたのコントローラに追加したクラスを持っていなかった場合

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

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

てみてください:だからwhere()を使用しようと

use DB; 
+0

ことデバイスではなく店舗数を返します。 –

関連する問題