我有以下表格:
users
- id
- username
kids
- id
- user_id
groups
- id
group_user
- id
- group_id
- user_id
sits
- id
- user_id
他们当然有addl字段,但这只是无关的信息。
我的用户模型包含:
public function kids()
{
return $this->hasMany('Kid');
}
public function sits()
{
return $this->hasMany('Sit');
}
public function groups()
{
return $this->belongsToMany('Group')->withPivot('status');
}
我的UserController @ show方法如下所示:
public function show($user)
{
$user = User::find($user)->load('kids', 'groups', 'sits');
return $user;
}
所以,当我点击/user/show/1
时,我得到了我期望的JSON。
{
"id": "1",
"username": "somename",
"email": "somename@example.com",
"kids": [
{
"id": "4",
"user_id": "1"
},
{
"id": "3",
"user_id": "1"
},
{
"id": "1",
"user_id": "1"
}
],
"groups": [
{
"id": "1",
"name": "Group Name",
"pivot": {
"user_id": "1",
"group_id": "1"
}
}
],
"sits": [
{
"id": "2",
"user_id": "1",
"start": "2014-01-16 00:00:31",
"end": "2014-01-16 00:00:31",
"sitter_id": "2"
}
]
}
但我的问题是,为此过滤添加另一个对象的“Laravel Way”是什么?假设我想要返回sits
,还要upcomingSits
返回某个“开始”日期或“sitter_id”= 0的位置。
对于那种逻辑,适当的MVC方法在哪里?如何使用Laravel在此响应中返回它?
答案 0 :(得分:0)
您可以这样做:
$user = User::with('kids', 'groups', 'sits')->find($user_id)->toArray();
$sits = Sit::where(.....)->get()->toArray();
return Response::json(array(
'user' => $user,
'sits' => $sits
));