如何获取所有(父)数据并加载它们的子数据(急切加载)但在父列上有条件?

How to get all (parent) data and load their children data (eager load) but with condition on parent column?

假设我只想在 user.status 为真时获取所有用户及其帖子。

如何使用预先加载(即使用)来实现此目的

我想获取的数据:

{
"users": [
    {
        "id": 1,
        "status": false
    },
    {
        "id": 2,
        "status": false
    },
    {
        "id": 3,
        "status": true,
        "posts": [
            {
                "id": 1,
                "comment": "abc"
            },
            {
                "id": 2,
                "comment": "abc"
            },
            {
                "id": 3,
                "comment": "abc"
            }
        ]
    }
]

}

您可以通过加载所有用户,然后过滤您要加载的用户,最后加载他们的关系来轻松实现这一点。

$users = User::all();
$users->filter->status->load('posts');

如果您使用的是相当现代的 Laravel 版本,您可能需要查看有关 API 资源的文档:

https://laravel.com/docs/7.x/eloquent-resources


条件关系 docs

尝试这样的事情:

/**
 * Transform the resource into an array.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return array
 */
public function toArray($request)
{
    return [
        ...
        'posts' => $this->when((bool) $this->status, PostResource::collection($this->whenLoaded('posts'))),
        ...
    ];
}