Laravel渴望加载资源集合

问题描述 投票:-1回答:1

我如何急切加载资源集合关系?我做了一个叫gravel_pits关系的资源

class GravelTypeResource extends Resource
{
    public function toArray($request)
    {
        return [
            'id'          => $this->id,
            'name'        => $this->name,
            'deleted_at'  => $this->deleted_at,
            'gravel_pits' => $this->gravel_pits,
        ];
    }
}

关于模型M:M的关系:

public function gravel_pits()
{
    return $this->belongsToMany('App\GravelPit');
}

从API我得到它像这样:

public function index()
{
    return GravelTypeResource::collection(GravelType::all());
}

我可以通过这样做来急切地加载它

public function index()
{
    return GravelTypeResource::collection(GravelType::with('gravel_pits'));
}

哪个有效...但是我无法控制砾石坑的实际需要的属性,相反,急切的负载将它们全部取出。有一个简单的解决方法吗?

php laravel eager-loading
1个回答
0
投票

您可以传入选择以获取所需的字段。只需确保获得关系所基于的字段:

return GravelTypeResource::collection(GravelType::with('gravel_pits'=>function($query) {
     $query->select(['id', 'gravel_type_id', 'column3', 'column4']);
});
© www.soinside.com 2019 - 2024. All rights reserved.