【问题标题】:Laravel: JSON and pivot tableLaravel:JSON 和数据透视表
【发布时间】:2016-10-18 02:44:55
【问题描述】:

很抱歉标题不解释,但我想不出一个描述性的标题。

我有以下 3 个表: - 游戏 - 平台 - 游戏平台

我在 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 来做这一切。

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

【问题讨论】:

标签: php json laravel eloquent lumen


【解决方案1】:

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

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

【讨论】:

  • 太棒了,这就是我一直在寻找的。谢谢。
  • @Serellyn 很高兴我能帮上忙
【解决方案2】:

我知道这已经得到解答,但我相信正确的答案是将您想要隐藏的任何内容添加到模型上的 hidden 属性中。

<?php
class Games extends Eloquent
{
    protected $hidden = ['pivot.game_id', 'pivot.platform_id'];
}

我不确定您的密钥是什么,因为它们在您的两个示例中有所不同。 请看:https://github.com/laravel/framework/issues/745

【讨论】:

    【解决方案3】:

    更好的方法是使用 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());
    

    【讨论】:

      猜你喜欢
      • 2016-08-08
      • 2021-08-17
      • 2018-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-04
      • 1970-01-01
      相关资源
      最近更新 更多