使用 $this->response->collection 返回空数组的时候会报错

经常使用$this->response->collection来返回筛选到的一组列表数组,但如果这个数组是空的,就会发生报错
如以下代码

$category = Category::where('organization_id', $organization_id)->where('up_id', $specialty_category_info->id)->get();
return $this->response->collection($category, new CategoryTransformer());

通过条件筛选出一组分类列表,分类列表可能是空,经测试,为空数组时报错,不为空时全部正常,报错摘要如下:

"message": "Type error: Argument 1 passed to Dingo\\Api\\Http\\Response\\Factory::collection() must be an instance of Illuminate\\Support\\Collection, array given, called in /www/wwwroot/app/Http/Controllers/Api/V1/AboutController.php on line 159",
"status_code": 500,

希望能告知这是正常现象,需要我手动去判断,还是有某个地方没处理好导致的,谢谢

《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
liyu001989
最佳答案
$category = Category::where('organization_id', $organization_id)->where('up_id', $specialty_category_info->id)->get();
return $this->response->collection($category, new CategoryTransformer());

这么写应该不会报错,你加的判断反而不对啊。 本身没有数据,返回的就是 colleciton啊 。

collect 方法创建 collection

4年前 评论
讨论数量: 5
liyu001989

5.5 返回的都是 collection 了吧,你用的什么版本的 laravel

4年前 评论

@liyu001989
我好像明白了原因,我把thinkphp中的一些思想带到了这里面,天真的以为collection为空就是空数组,其实空collection跟空数组是不一样的,我这个理解应该是对的吧?

if($specialty_category_info){
    $category = Category::where('organization_id', $organization_id)->where('up_id', $specialty_category_info->id)->get();
}else{
    $category = array();
}
return $this->response->collection($category, new CategoryTransformer());

顺便再问一句,有没有办法创建空collection?

4年前 评论
liyu001989
$category = Category::where('organization_id', $organization_id)->where('up_id', $specialty_category_info->id)->get();
return $this->response->collection($category, new CategoryTransformer());

这么写应该不会报错,你加的判断反而不对啊。 本身没有数据,返回的就是 colleciton啊 。

collect 方法创建 collection

4年前 评论

@liyu001989 明白了,感谢

4年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!