Murlidhar Fichadia Murlidhar Fichadia - 6 months ago 8
SQL Question

count and check json query result

I am handling three scenarios :

1) If query returns no result
2) if query returns one result
3) if query returns two or more result

This is my query :

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


I get $events in json format like this :

[] = 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


If you see that 0,1 and 3. thats what I want to know for a given resultant query.
I need to check if the above result has how many results. How can I find this

Because this is how I am handling the scenarios :

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.
}

Answer

If I understood you correctly, you need to count() them:

$numberOfResults = count($events);
Comments