我有一个类似于
的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关系的表,那么这将更容易,但这不是这里的情况。 怎么能实现这一目标?
答案 0 :(得分:2)
检查这是否有效。我没有尝试,但根据文档,我们可以添加访问者和变异器。但它会改变您对模型所做的每一个响应。
// 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
时,会提供raceStart
和raceEnd
值。
参考: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
$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);