cheersjosh
cheersjosh

Reputation: 1209

Laravel: Return a database query result using the MySQL SUM function and store it in a variable

I need assistance on how to return results from database queries using the MySQL SUM() function with Laravel. I know I need to use raw database queries and I've tried that but it seems to only return me an array.

This is the code I have so far:

$cron_jobs = DB::select('
      SELECT ROUND(SUM((TIME_TO_SEC(TIMEDIFF(end_time, start_time))/60)/15))
      AS cron_jobs
      FROM `quiet_periods`');

var_dump($cron_jobs);
exit;

And this is my console log:

array(1) {
  [0]=>
  object(stdClass)#689 (1) {
    [cron_jobs]=>
    string(2) "20"
  }
}

The objective for me is to pull the value 20 from the returned result yet I can't seem to achieve this. When I run the following code:

echo $cron_jobs;

It should only show the value of the key / value pair.

Please note: I have also used DB::statement yet that returns the result of 1 which I am assuming is a Boolean result. I don't get why though... Oh, and I have used DB::raw within the DB::select but that only seems to return the same result.

Upvotes: 2

Views: 3866

Answers (2)

chickenchilli
chickenchilli

Reputation: 3548

I don't know what Laravel version we are talking, but in 4 you got:

DB::selectOne($sql);

Upvotes: 1

David Barker
David Barker

Reputation: 14620

Use standard accessors to get to your data

$crons = $cron_jobs[0]->cron_jobs;

Upvotes: 5

Related Questions