在Laravel中,当函数将对象返回到视图时,'hasMany'相关对象不会与对象一起发送。
这是控制器功能代码:
return Response::json(array('success'=>true, 'res'=>Group::find($group->id)->toArray()));
这就是输出:
{"success":true,"res":{"id":18,"title":"My PCs","notes":"This is my PCs.","user_id":1}}
这是组模型中的关系函数:
public function devices() {
return $this->hasMany('Device');
}
为什么我无法在视图中获取组对象的设备?
答案 0 :(得分:0)
首先需要eager or lazy load关系:
// lazy load if you already fetched the $group
$group->load('devices');
return Response::json(array('success'=>true, 'res'=>$group->toArray()));
// eager load when fetching the $group
$group = Group::with('devices')->find($someId);
return Response::json(array('success'=>true, 'res'=>$group->toArray()));