Laravel:JSON 和枢轴 table

Laravel: JSON and pivot table

抱歉 non-explanatory 标题,但我想不出一个描述性的标题。

我有以下 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');
}

现在这很有用,我得到一个 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"
        }
    }]
}]

现在我的问题如下。我不想显示整个 'pivot' 信息,只显示 'release_date',像这样:

"platforms": [{
        "id": 4,
        "name": "PC",
        "release_date": "2016-03-03"

在 Laravel 中有没有简单的方法来做这样的事情?据我现在所见,看看其他帖子,要么编写一个将 json 转换为数组的函数,然后我可以对其进行排列。或者我可以编写自己的查询,而不是让 Laravel 做所有这些事情。

希望你们能帮我解决这个问题。谢谢!

我将通过集合上的方法修改查询返回的数据 class:

//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());