Friday, January 28, 2022

[FIXED] Using Find with field 'as' is splitting my objects

Issue

For example, if I do this:

...
$parameters['fields'] = array('*','UNIX_TIMESTAMP(time_seen) as time_epoch');
$this->{$this->modelClass}->find('all', $parameters);
...

I'm ending up with something like this:

[
  {
    "0": {
      "time_epoch": "1457623605"
    },
    "Foo": {
      "ID": "106"
      ...
    }
  },
  ...

When I'm hoping for this:

[
  {
    "Foo": {
      "time_epoch": "1457623605"
      "ID": "106"
      ...
    }
  },
  ...

I suppose I could still work with this as they share a parent object... but I'd rather just do like..

foreach ( $foos as $foo ) :
    $foo = $foo->Foo;
    ...
    print $foo['time_epoch'];
    ...
    print $foo['ID'];
    ...

than something like...

foreach ( $foos as $foo ) :
    $foo = (array)$foo; //because i can't access $foo->0
    $epoch = $foo[0]["time_epoch"];
    $foo = $foo["Foo"];
    ...
    print $epoch;
    ...
    print $foo['ID'];
    ...

Solution

This is a pretty tricky situation in CakePHP. By writing it the way you did, within the "fields" index, it's forced to be under a random key 0 since it's unaware which model this "time_epoch" is a part of.

One possible solution to this is the concept of virtual fields. You could try something like this:

 $this->{$this->modelClass}->virtualFields['time_epoch'] = "UNIX_TIMESTAMP(time_seen)"; // Add this
 $this->{$this->modelClass}->find('all', $parameters);
 ...

You may want to check this out- Creating virtual fields on the fly

This will fix your issue and return your array the way you're expecting.

Peace! xD



Answered By - Object Manipulator

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.