我很难构建并返回嵌套的json。我想从两个与id连接的不同表中获取信息。
这是我的情况:
在我的控制器上使用此方法:
public function eventOccList(EventOccurrence $eventOccurrence){
return new EventOccurrenceResourceCollection(EventOccurrence::all());
}
并使用EventOccurrenceResource类中的映射
return [
'type' => 'event',
'id' => (string) $this->id,
'name' => $this->name,
'description' => $this->description,
'location_id' => $this->location_id
];
我获得了这个JSON:
{“data”:[{“type”:“event”,“id”:“1”,“name”:“event_1”,“description”:“event blabla”,“location_id”:11}
如果我想获取关于表“location”的所有关于id“location_id”的信息并在同一个json中显示,那么检索这些数据的最佳方法是什么?
谢谢 !
我假设您的事件模型具有位置关系:
public function location{
return $this->belongsTo(Event::class);
}
您可以在控制器中完成活动后执行此操作:
$event->load('location');
return $event->toJson();
然后,您可以隐藏或追加您想要的任何属性:)