简体   繁体   English

Laravel 4:模型或控制器中的子句在哪里?

[英]Laravel 4: Where Clause in Model or in Controller?

I have the following tables: 我有以下表格:

users
  - id
  - username

kids
 - id
 - user_id

groups
 - id

group_user
 - id
 - group_id
 - user_id

sits
 - id
 - user_id

They of course have addl fields, but it's just extraneous info. 他们当然有addl字段,但这只是无关的信息。

My User model contains: 我的用户模型包含:

public function kids()
{
    return $this->hasMany('Kid');
}

public function sits()
{
    return $this->hasMany('Sit');
}

public function groups()
{
    return $this->belongsToMany('Group')->withPivot('status');
}

My UserController@show method looks like this: 我的UserController @ show方法如下所示:

public function show($user)
{
    $user = User::find($user)->load('kids', 'groups', 'sits');
    return $user;
}

So, when I hit /user/show/1 I get the JSON I expect. 因此,当我点击/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"
    }
  ]
}

But my question is what is the "Laravel Way" to add another object to this response that is filtered? 但是我的问题是向此已过滤响应添加另一个对象的“ Laravel方式”是什么? Let's say I wanted to return sits but also upcomingSits where it was filtered by a certain "start" date or where "sitter_id"=0. 假设我要返回sits但也要返回upcomingSits Sits,该位置已按某个“开始”日期进行了过滤,或者“ sitter_id” = 0。

Where is the proper MVC approach for that sort of logic and how would I use Laravel to return it in this response? 那种逻辑的正确MVC方法在哪里,我将如何使用Laravel在此响应中返回它?

You can do something like this: 您可以执行以下操作:

$user = User::with('kids', 'groups', 'sits')->find($user_id)->toArray();
$sits = Sit::where(.....)->get()->toArray(); 

return Response::json(array(
    'user' => $user,
    'sits' => $sits
));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM