计算并检查json查询结果

时间:2016-05-06 10:49:21

标签: php mysql json laravel

我正在处理三种情况:

1)如果查询没有返回结果 2)如果查询返回一个结果 3)如果查询返回两个或多个结果

这是我的疑问:

$events = DB::table('bookings')
             ->join('events','bookings.event_id','=','events.id')
             ->join('spots','bookings.spot_id','=','spots.id')
             ->join(DB::raw('(select S.event_id,sum(S.spaces) as sum_spaces from spots S group by S.event_id) d'), function($join)
             {
                $join->on('bookings.event_id', '=', 'd.event_id');
             })
             ->select('bookings.event_id','events.name', 'spots.event_date','d.sum_spaces',
                      DB::raw('COUNT(bookings.event_id) as tb'))
             ->groupBy('bookings.event_id')
             ->get();

我以json格式获取$ events:

[]  = 0
[{"event_id":1,"name":"Yoga","event_date":"2016-05-02","sum_spaces":"450","tb":6}] = 1
[{"event_id":1,"name":"Yoga","event_date":"2016-05-02","sum_spaces":"100","tb":16},{"event_id":2,"name":"Yoga","event_date":"2016-05-02","sum_spaces":"450","tb":6},{"event_id":3,"name":"blah","event_date":"2016-05-02","sum_spaces":"250","tb":6}] = 3

如果你看到0,1和3.这就是我想知道的给定结果查询。 我需要检查上面的结果是否有多少结果。我怎样才能找到这个

因为这就是我处理场景的方式:

if(empty($events))
{
 //sets default value
}
else if(check if $results have one and only one result)
{
 //Do something
}
else
{
  //here I can handle if $events query have more than one result.
}

1 个答案:

答案 0 :(得分:2)

如果我理解正确,您需要count()他们:

$numberOfResults = count($events);