API资源中的Laravel多级关系 [英] Laravel Multi level relationship in API Resource
问题描述
我的问题是,我确实不需要加载api资源.查看我的Api资源文件
My problem is, the api resource loading which i really not needed. Look into my Api Resource files
//BoxItemResource.php
//BoxItemResource.php
public function toArray($request)
{
return [
'box_id'=> $this->box_id,
'item_id'=> $this->item_id,
'item'=> new ItemResource($this->item)
];
}
//ItemResource.php
//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
//ConditionResource.php
public function toArray($request)
{
return [
'id'=> $this->id,
'name'=> $this->name
];
}
//控制器
return BoxItemResource::collection(
BoxItem::with([
'item'
])->paginate(1)
);
我的问题是,我只需要BoxItem和Item.我真的不想加载条件.如果我从ItemResource.php中删除条件关系,它将起作用.但是问题是我在需要此条件的其他地方使用了ItemResource.php.
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.
更清楚地讲,我想加载我在controller(在-> with())中提到的关系.
more clearly, I want to load the relationship which I mention in controller(in ->with()) .
谢谢.
推荐答案
API资源允许条件关系.
对于属性,我认为足以用于您的情况,这意味着您可以将属性值简单地包装在 $ this-> when($ condition,$ value)
和如果 $ condition == false
,整个属性将从结果中删除.下面是您的代码的具体示例:
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'))
];
这篇关于API资源中的Laravel多级关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!