我如何急切加载资源集合关系?我做了一个叫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'));
}
哪个有效...但是我无法控制砾石坑的实际需要的属性,相反,急切的负载将它们全部取出。有一个简单的解决方法吗?
您可以传入选择以获取所需的字段。只需确保获得关系所基于的字段:
return GravelTypeResource::collection(GravelType::with('gravel_pits'=>function($query) {
$query->select(['id', 'gravel_type_id', 'column3', 'column4']);
});