如何使用 laravel 从 json 中删除 pivot 关键字?

问题描述 投票:0回答:4

我正在尝试从具有数据透视表

games
user_games
表中获取数据。下面的代码如果适合我

$UserGames = User::with(['games' => function ($query){
    $query->withPivot('highscore','level');
}])->find(request()->user()->id);

我得到以下 json 响应

{
    "data": [
        {
            "id": 2,
            "name": "culpa",
            "type_id": 3,
            "created_at": "2018-10-30 11:23:27",
            "updated_at": "2018-10-30 11:23:27",
            "pivot": {
                "user_id": 2,
                "game_id": 2,
                "highscore": 702,
                "level": 3
            }
        }
    ]
}

但我想从上面的 json 中删除

pivot
关键字并将数据透视细节拉入根目录,就像我的愿望响应下面一样

{
    "data": [
        {
            "id": 2,
            "name": "culpa",
            "type_id": 3,
            "created_at": "2018-10-30 11:23:27",
            "updated_at": "2018-10-30 11:23:27",
            "user_id": 2,
            "highscore": 702,
            "level": 3
        }
    ]
}

有人可以指导我如何解决这个问题。我将不胜感激。非常感谢

php laravel laravel-5.6
4个回答
2
投票

您可以在数据透视模型上使用

hidden
appends
来重新构造返回的数据。

class PivotModel extends model
{
    protected $hidden = ['pivot'];
    protected $appends = ['user_id'];

    public function getUserIdAttribute()
    {
        return $this->pivot->user_id;
    }
}

参考隐藏

参考appends


0
投票

您可以将 json 转换为数组,而不是将其重新转换为 json。

$UserGames = User::with(['games' => function ($query){
    $query->withPivot('highscore','level');
}])->find(request()->user()->id);

$UserGames = json_decode($UserGames, true);

$pivot = $UserGames['data'][0]['pivot'];

unset($UserGames['data'][0]['pivot']);

$UserGames = json_encode(array_merge($UserGames[0], $pivot));

0
投票

您可以重写

User
模型的
jsonSerialize
方法,该方法在
toJson
方法中调用,这是初始方法体:

public function jsonSerialize()
{
    return $this->toArray();
}

你可以这样做:

public function jsonSerialize()
{
    $attrs = $this->toArray();

    if (isset($attrs['pivot'])) {
        $attrs = array_merge($attrs, $attrs['pivot']);
        unset($attrs['pivot']);
    }

    return $attrs;
}

0
投票

强烈推荐使用API Resource修改响应层

对于这个问题,使用

php artisan make:resource UserGameResource

创建一个api资源
public function toArray($request)
{
    'id' => $this->id,
    'name' => $this->name,
    'type_id' => $this->type_id,
    'created_at' => $this->created_at,
    'updated_at' => $this->updated_at,
    'user_id' => $this->pivot->user_id,
    'highscore' => $this->pivot->highscore,
    'level' => $this->pivot->level,
}

最后使用此 api 资源返回您的查询结果:

$UserGames = <your query>
$response = UserGamesResource::collection($UserGames);
© www.soinside.com 2019 - 2024. All rights reserved.