使用 $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,

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

《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
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

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

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

5年前 评论

@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?

5年前 评论
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

5年前 评论

@liyu001989 明白了,感谢

5年前 评论

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