Ser*_*lyn 7 php json laravel eloquent lumen
对于不解释的标题感到抱歉,但我无法想出一个描述性的标题.
我有以下3个表: - 游戏 - 平台 - games_platforms
而且我在Laravel中有2个平台和游戏模型.
public function games()
{
return $this->belongsToMany('App\Game', 'games_platforms')->withPivot('release_date');
}
public function platforms()
{
return $this->belongsToMany('App\Platform', 'games_platforms')->withPivot('release_date');
}
Run Code Online (Sandbox Code Playgroud)
现在这就像一个魅力,我得到一个JSON字符串,其中包含3个表中的所有信息,就像这样.
[{
"id": 1,
"name": "Borderlands",
"short_description": "",
"created_at": null,
"updated_at": null,
"platforms": [{
"id": 4,
"name": "PC",
"pivot": {
"game_id": 1,
"platform_id": 4,
"release_date": "2016-03-03"
}
}]
}]
Run Code Online (Sandbox Code Playgroud)
现在我的问题如下.我不想显示整个'pivot'信息,只是'release_date',如下所示:
"platforms": [{
"id": 4,
"name": "PC",
"release_date": "2016-03-03"
Run Code Online (Sandbox Code Playgroud)
在Laravel有一个简单的方法来做这样的事吗?就我现在所看到的,看看其他帖子,是要么写一个函数将json变成一个数组,然后我可以安排它.或者我可以编写自己的查询,而不是让Laravel完成所有这些.
希望你们能帮我解决这个问题.谢谢!
我将通过集合类上的方法修改从查询返回的数据:
//replace Game::all() with your actual query
return Game::all()->each(function($game){
$game->platforms->map(function($platform){
$platform->release_date = $platform->pivot->release_date;
unset($platform->pivot);
return $platform;
});
});
Run Code Online (Sandbox Code Playgroud)