douren6874 2017-12-19 16:06
浏览 37

嵌套的json laravel 5.5

I have difficult to build and return a nested json. I want obtain the information from two differents table joined with an id.

This is my situation:

With this method on my controller:

public function eventOccList(EventOccurrence $eventOccurrence){
    return new EventOccurrenceResourceCollection(EventOccurrence::all());
}

and with the mapping in the class EventOccurrenceResource

return [
    'type' => 'event',
    'id' => (string) $this->id,
    'name' => $this->name,
    'description' => $this->description,
    'location_id' => $this->location_id
]; 

I obtain this JSON:

{"data":[{"type":"event","id":"1","name":"event_1","description":"event blabla","location_id":11}

If I want to obtain all the informations about the table "location" with the id "location_id" and show in the same json, what is the best way to retrieved this data?

Thanks !

  • 写回答

1条回答 默认 最新

  • dongliyun3301 2017-12-19 16:15
    关注

    I assume your Event Model have a location relationship :

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

    you can do this once you have your event in a Controller :

    $event->load('location');
    
    return $event->toJson();
    

    You can then hide or append any attribute you want :)

    评论

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀