gpt4 book ai didi

laravel - 转换 Laravel Eloquent 结果

转载 作者:行者123 更新时间:2023-12-04 02:21:30 25 4
gpt4 key购买 nike

当我在我的 Controller 中执行它时

$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 结果的正确方法。

最佳答案

您可以使用 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']);

关于laravel - 转换 Laravel Eloquent 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28729796/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com