Laravel Multi level relationship in API Resource

巧了我就是萌 提交于 2021-02-11 16:50:16

问题


My problem is, the api resource loading which i really not needed. Look into my Api Resource files

//BoxItemResource.php

 public function toArray($request)
{
    return [
        'box_id'=> $this->box_id,
        'item_id'=> $this->item_id,
        'item'=> new ItemResource($this->item)
    ];
}

//ItemResource.php

public function toArray($request)
{
    return [
        'id' => $this->id,
        'shipping_price' => $this->shipping_price,
        'condition_id' => $this->condition_id,
        'condition' => new ConditionResource($this->condition)
    ];
}

//ConditionResource.php

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

//controller

return BoxItemResource::collection(
        BoxItem::with([
            'item'
        ])->paginate(1)
    );

My problem is, I just need only BoxItem and Item here. I don't really want to load condition. If i remove the condition relation from ItemResource.php, it will work. but the problem is I am using the ItemResource.php in some other place which need this condition.

Is it possible to deny loading condition relation ship here.

more clearly, I want to load the relationship which I mention in controller(in ->with()) .

Thanks in advance.


回答1:


API resources allow for conditional attribtues and conditional relationships.

For attributes, which in my opinion is sufficient to use in your case, this means you can simply wrap the attribute value in $this->when($condition, $value) and the whole attribute will be removed from the result if $condition == false. So a concrete example of your code:

return [
    'box_id'=> $this->box_id,
    'item_id'=> $this->item_id,
    'item'=> $this->when($this->relationLoaded('item'), new ItemResource($this->item))
];

Or if you prefer using the relationship style:

return [
    'box_id'=> $this->box_id,
    'item_id'=> $this->item_id,
    'item'=> new ItemResource($this->whenLoaded('item'))
];



回答2:


Maybe you are looking for Conditional Relationships?

Ideally, it should look like the following:

public function toArray($request)
{
    return [
        'box_id'=> $this->box_id,
        'item' => ItemResource::collection($this->whenLoaded('item'))
    ];
}

The item key will only be present if the relationship has been loaded.



来源:https://stackoverflow.com/questions/54435479/laravel-multi-level-relationship-in-api-resource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!