benhowdle89
benhowdle89

Reputation: 37504

CakePHP query array

I am running this query using CakePHP:

$total = $this->Lapse->query("select sum(unix_timestamp(stop) - unix_timestamp(start)) from lapses where id = ".$lastId."");

And i get back this array structure:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [sum(unix_timestamp(stop) - unix_timestamp(start))] => 1
                )

        )

)

So my variable holds this: $updateVal = $total[0][0][0];

Which isn't the prettiest, is there a way i can simplify this OTT array?

Upvotes: 0

Views: 694

Answers (1)

elitalon
elitalon

Reputation: 9447

Have you tried the find() method passing a custom fields option?:

$this->Lapse->find('all', array(
  'fields' => array('sum(unix_timestamp(stop) - unix_timestamp(start)) as elapsed_time'),
  'conditions' => array('Lapse.id' => $lastId),
));

The returned array is prettier than the one you're getting, although it's not prettier than elapsed_time being an actual model property.

Another solution would be to set elapsed_time as a virtual field within the model:

class Lapse extends AppModel {
  ...

  public $virtualFields = array(
    'elapsed_time' => 'sum(unix_timestamp(Lapse.stop) - unix_timestamp(Lapse.start)',
  );

  ...
}

Then elapsed_time acts as a model property and would be returned as $updateVal['Lapse']['elapsed_time'] in every find() call.

Upvotes: 3

Related Questions