You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中如何合并Resource Collection并返回单一响应元素?

解决方案

问题原因

$this->first 和 $this->second 是 Eloquent Collection 实例,并非原生PHP数组,直接使用 array_merge() 会报错,因为该函数仅支持数组类型的参数。

正确实现方式

根据你的需求选择以下方法:

方法1:合并集合(自动处理重复主键)

使用Collection内置的 merge() 方法,合并两个集合时,若存在主键相同的模型,第二个集合的模型会覆盖第一个:

class TestingResource extends JsonResource
{
    public function toArray($request)
    {
        $combined = $this->first->merge($this->second);
        
        return [
            'combined' => AnotherResource::collection($combined),
        ];
    }
}

方法2:拼接集合(保留所有元素)

如果需要完整保留两个集合的所有元素(包括主键重复的模型),使用 concat() 方法,它会直接将第二个集合的元素追加到第一个集合末尾:

class TestingResource extends JsonResource
{
    public function toArray($request)
    {
        $combined = $this->first->concat($this->second);
        
        return [
            'combined' => AnotherResource::collection($combined),
        ];
    }
}

方法3:转数组后合并(兼容原生数组操作)

若一定要用 array_merge(),可先将集合转为数组,再重新包装成Collection:

class TestingResource extends JsonResource
{
    public function toArray($request)
    {
        $combinedArray = array_merge($this->first->toArray(), $this->second->toArray());
        $combined = collect($combinedArray);
        
        return [
            'combined' => AnotherResource::collection($combined),
        ];
    }
}

注意事项

如果 first 和 second 是模型的关联关系,建议在控制器查询时提前预加载关联(例如 Model::with(['first', 'second'])->find($id)),避免出现N+1查询性能问题。

内容的提问来源于stack exchange,提问作者BigJobbies

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 07:35:21