在laravel雄辩的结果中添加额外的键

时间:2017-07-04 17:15:23

标签: php eloquent laravel-5.4

我有一个类似于

的laravel查询构建器结果
{
  "data": [
    {
      "id": "",
      "awardID": 2,
      "title": "Dummy title",
      "status": "active",
      "raceStart":"",
      "raceEnd:":""
    }
  ]
}      

我想输出的是这样的

{
  "data": [
    {
      "id": "",
      "awardID": 2,
      "title": "Dummy title",
      "status": "active",
      "period": {
        "raceStart":"",
        "raceEnd:":""
      }
    }
  ]
} 

如果句点是与父表具有1比1关系的表,那么这将更容易,但这不是这里的情况。 怎么能实现这一目标?

1 个答案:

答案 0 :(得分:2)

检查这是否有效。我没有尝试,但根据文档,我们可以添加访问者和变异器。但它会改变您对模型所做的每一个响应。

使用Eloquent

// Your Model
class Race extends Model
{
    {...}
    protected $appends = ['period'];
    // accessor
    public function getPeriodAttribute($value)
    {  
        $this->attributes['period'] = (object)[];
        $this->attributes['period']['raceStart'] = $this->attributes['raceStart'];
        $this->attributes['period']['raceEnd'] = $this->attributes['raceEnd'];
        unset($this->attributes['raceStart']); = $value;
        unset($this->attributes['raceEnd']);
        return $this->attributes['period'];
    }
}

现在,当您访问$race->period时,会提供raceStartraceEnd值。

参考:https://laravel.com/docs/5.4/eloquent-mutators#accessors-and-mutators

否则另一个选项是查询后,执行map

{...}
->map(function($data) {
    $data->period = (object)[];
    $data->period['raceStart'] = $data->raceStart;
    $data->period['raceEnd'] = $data->raceEnd;
    unset($data->raceStart);
    unset($data->raceEnd);
    return $data;
});

参考:https://laravel.com/docs/5.4/eloquent-collections#introduction

使用QueryBuilder

$races = DB::table('races')->get();

$races = array_map(function ($data) {
    $data->period = (object)[
        "raceStart" => $data->raceStart,
        "raceEnd" => $data->raceEnd
    ];
    unset($data->raceStart);
    unset($data->raceEnd);
    return $data;
}, $races->data);