API Resource 中拼接额外数据
class IndexResource extends JsonResource {
public function toArray($request) {
// 将数组拼接到 ItemResource 中
$all_category = [
'id' => 0,
'title' => '全部',
'order' => "99999"
];
return [
'items' => ItemsResource::collection(Item::all())->concat(
$all_category
),
];
}
}
concat()
在结果最后一个,prepend()
在结果第一个。
从楼主命名看,应该是针对接口定义的
ApiResource
。借帖子问一下大家如何使用
ApiResource
。我们目前大部分情况是根据模型创建ApiResource
,导致的问题是:在模型查询约束了字段或预加载关系时,需要用做大量的判断,如:
这样做的好处自然是可以在不同接口保持资源输出结构统一,但缺点就是这个类型的代码过于臃肿。