如何使用FuelPHP的ORM和Controller_Rest返回JSON数组而不是对象 [英] How do I return JSON Arrays instead of objects using FuelPHP's ORM and Controller_Rest

查看:125
本文介绍了如何使用FuelPHP的ORM和Controller_Rest返回JSON数组而不是对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

返回:

{
  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
    }
  ]
}

之所以会发生这种情况,是因为ORM返回具有与记录的PKEY相对应的键的相关结果数组,并且JSON将其解释为Object.我希望这些数组通过array_values()之类的东西,所以JSON结果将使用Array.

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.

我只希望顺序排列所有一对多数组,而不是通过记录PKEY.

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

推荐答案

总之:除非您在Query:hydrate

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.

这篇关于如何使用FuelPHP的ORM和Controller_Rest返回JSON数组而不是对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆