具有Api资源的嵌套BelongsToMany中的热切负荷枢轴

时间:2019-05-17 18:52:35

标签: php laravel api pivot many-to-many

我需要你的帮助!

使用 ApiResources 时,我在返回数据透视表信息时遇到问题。

如果我有这样的模型:

Post.php

public function likes()
{
    return $this->belongsToMany(Like::class)
        ->withPivot(['points']) // I want this in my PostResource::collection !
}

在定义其资源时:

LikeResource.php

public function toArray($request)
{
    return [
        'like_field' => $this->like_field
    ];
}

PostResource.php

public function toArray($request)
{
    return [ 
        'title' => $this->title,
        'likes' => LikeResource::collection($this->whenLoaded('likes'))
    ];
}

然后在 PostController.php

return PostResource::collection(Post::with('likes')->get())

它将返回如下内容:

控制器响应

[
    {
        'title' => 'Post 1'
        'likes' => [
            {
                'like_field' => 'Test'
            },
            {
                'like_field' => 'Test 2'
            }
        ]
    },
    {
        'title' => 'Post 2',
        ...
    }
]

问题在于,使用该LikeResource::collection()不会附加枢轴信息。定义 PostResource 时,如何添加数据透视表的“点”

仅此而已, 谢谢!

解决方案

好吧,只需阅读Laravel Docs中的一点,即可返回枢轴信息,您只需使用方法$this->whenPivotLoaded()

因此, PostResource 变为:

public function toArray($request)
{
    return [ 
        'title' => $this->title,
        'likes' => LikeResource::collection($this->whenLoaded('likes')),
        'like_post' => $this->whenPivotLoaded('like_post', function() {
            return $this->pivot->like_field;
        })
    ];
}

0 个答案:

没有答案