对不起的标题很抱歉,但我无法提出一个描述性的标题。
我有以下3个表: - 游戏 - 平台 -games_platforms
我在Laravel中有2种平台和游戏的模型。
public function games()
{
return $this->belongsToMany('AppGame', 'games_platforms')->withPivot('release_date');
}
public function platforms()
{
return $this->belongsToMany('AppPlatform', 'games_platforms')->withPivot('release_date');
}
现在,这就像魅力一样,我得到了一个带有3个表中所有信息的JSON字符串。
[{
"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"
}
}]
}]
现在我的问题如下。我不想显示整个"枢轴"信息,只有" Release_date",例如:
"platforms": [{
"id": 4,
"name": "PC",
"release_date": "2016-03-03"
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;
});
});
我知道这已经回答了,但我相信正确的答案是将您想隐藏到模型上隐藏的属性中的所有内容。
<?php
class Games extends Eloquent
{
protected $hidden = ['pivot.game_id', 'pivot.platform_id'];
}
我不确定您的密钥是什么,因为它们在您的两个示例中有所不同。请参阅:https://github.com/laravel/framework/issues/745
一种更好的方法是使用laravel资源,
首先创建资源(php artisan make:resource
)
Rresource GameResource extends Resource
{
public function toArray($request)
{
return [
'release_date' => $this->pivot->release_date,
'name' => $this->name,
/// All other fields or you can merge both here
];
}
}
现在使用此资源;
$data = GameResource::collection(Game::all());