1

guid我在计算不为空的设备数量时遇到问题。

它需要按用户获取所有商店user_id,然后计算所有guid不为空的设备。

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

但它需要计算guid不为空的位置。

我也很想知道是否有其他reduce方法。

4

2 回答 2

1

因为$item->devices是一个集合,所以没有whereNotNull()集合。所以尝试使用where()

$item->devices->where('guid', '<>', null)->count();
于 2016-11-04T14:58:36.577 回答
0

尝试:

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

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

或者

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

$get_count = count($shops);

如果您没有在控制器上添加类 DB:

use DB;
于 2016-11-04T15:14:12.967 回答