变换Laravel Eloquent结果

时间:2015-02-25 21:18:55

标签: laravel eloquent

当我在我的控制器中执行此操作时

$data = User::with('teams')->find(2);
return response(['data' => $data]);

我得到了这个结果

{
        "id": 2,
        "country_id": 1,
        "first_name": "John",
        "last_name": "Doe",
        "created_at": "-0001-11-30 00:00:00",
        "updated_at": "2015-02-02 23:08:21",
        "full_name": "John Doe",
        "teams": [
            {
                "id": 1,
                "name": "Helpdesk medewerker",
                "description": ""
            },
            {
                "id": 2,
                "name": "Retentie",
                "description": ""
            }
        ]
    }

我对完整的teams数据不感兴趣,但只对用户的teamNames感兴趣。

我已经通过添加此

来完成此操作
$data->each(function($user) {
   $user->team_names = $user->teams->lists('name');
   unset($user->teams);
});

我想知道这是否是修改Eloquent结果的正确方法。

2 个答案:

答案 0 :(得分:0)

您可以使用attribute accessor。将其添加到您的模型中:

protected $hidden = ['teams']; // hide teams relation in JSON output
protected $appends = ['team_names']; // add custom attribute to JSON output

public function getTeamNamesAttribute(){
    return $this->teams->lists('name');
}

要动态更改hiddenappends,您可以使用setter方法:

$data = User::with('teams')->find(2);
$data->setHidden(['teams']);

答案 1 :(得分:0)

在第一次构建时过滤掉您想要的列。

$data = User::with(['teams' => function($query){
    return $query->select('name');
}])->find(2);

将输出:

{
    ...
    "teams": [
        {
            "name": "Helpdesk medewerker"
        },
        {
            "name": "Retentie"
        }
    ]
}

您还可以使用lists方法。

$data = User::with(['teams' => function($query){
    return $query->lists('name');
}])->find(2);

将输出:

{
    ...
    "teams": ["Helpdesk medewerker", "Retentie"]
}