嵌套的json laravel 5.5

问题描述 投票:0回答:1

我很难构建并返回嵌套的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中显示,那么检索这些数据的最佳方法是什么?

谢谢 !

php json laravel laravel-5 laravel-5.5
1个回答
1
投票

我假设您的事件模型具有位置关系:

public function location{
    return $this->belongsTo(Event::class);
}

您可以在控制器中完成活动后执行此操作:

$event->load('location');

return $event->toJson();

然后,您可以隐藏或追加您想要的任何属性:)

© www.soinside.com 2019 - 2024. All rights reserved.