Search code examples
fuelphpfuelphp-orm

How do I return JSON Arrays instead of objects using FuelPHP's ORM and Controller_Rest


Controller_Something extends Controller_Rest {
  public function get_something() {    
    $query = Model_Something::query()->related('hasMany')->get();
    return $this->response($query);
  }
}

Returns:

{
  stuff: here,
  looks: good,
  hasMany: {
    151251: {
      id: 151251,
      other: stuff
    }
  }
}

I want the relations as arrays:

{
  stuff: here,
  looks: good,
  hasMany: [
    {
      id: 151251,
      other: stuff
    }
  ]
}

This happens because the ORM returns related result arrays with keys corresponding to the record's PKEY, and JSON interprets this as an Object. I want these arrays to go through array_values() or something, so the JSON result will use Array.

Currently I am doing this to "solve" the problem:

$res = Format::forge($result_set)->to_array();
$res['hasMany'] = array_values($res['hasMany']);
return $this->response($res);

But this is only useful to one or two levels, where I know the data will be.

If there are relations that are not guaranteed, I don't what to have to error-check every potential subset of a complex Model.

I just want all the one-to-many arrays to be keyed sequentially instead of by the records PKEY.


Solution

  • In short: you can't unless you create a hook in Query:hydrate https://github.com/fuel/orm/blob/1.7/develop/classes/query.php#L1083, or shadowing the Query class with some implementation that returns the very same results except for hydrate.