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

a11xaf1n  于 2023-04-04  发布在  PHP
关注(0)|答案(4)|浏览(117)

我试图从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关键字,并将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
        }
    ]
}

有没有人能好心地指导我如何解决这个问题。我将不胜感激。非常感谢

rjzwgtxy

rjzwgtxy1#

您可以在pivot模型上使用hiddenappends来重新构造返回的数据。

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

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

隐藏的参考

    • 追加**参考
wnavrhmk

wnavrhmk2#

您可以将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));
kkih6yb8

kkih6yb83#

你可以覆盖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;
}
sd2nnvve

sd2nnvve4#

我强烈建议使用API资源来修改响应层。
对于此问题,请使用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);

相关问题