本文介绍了如何在分页资源上获取模型的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用Resource在流明上显示分页资源.
I want to display paginate resource on lumen using Resource.
我需要如下所示的json结果:
I need this shown as below json result:
{
"meta": {
"count": 10,
"total": 100
},
"links": {
"first": "http://localhost/page[limit]=10&page[offset]=0",
"last": "http://localhost/page[limit]=10&page[offset]=10",
"next": "http://localhost/page[limit]=10&page[offset]=10",
"prev": "null"
},
"data": [
{
"type": "items",
"id": "1"
}
]
}
这是我的控制器:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Item\Eloquent\ItemModel as ItemModel;
use App\Http\Resources\ItemsResource;
public function completeitems(Request $request)
{
$res = ItemModel::paginate();
return new ItemsResource($res);
}
?>
这是我的 ItemResource :
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\Resource;
class ItemsResource extends Resource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request
*
* @return array
*/
public function toArray($request)
{
return [
'type' => 'items',
'id' => $this->id
];
}
}
从我的代码中得出的结果是:
From my code the result is:
Undefined property: Illuminate\Pagination\LengthAwarePaginator::$id
我已经尝试了很多次,并在Google上搜索了错误但有点困惑.怎么解决呢?谢谢.
I have tried this many time and google the error but a bit confuse.How to solve this? Thank you.
推荐答案
使用collection()
方法返回多个模型:
Use the collection()
method to return multiple models:
public function completeitems(Request $request)
{
$res = ItemModel::paginate();
return ItemsResource::collection($res);
}
这篇关于如何在分页资源上获取模型的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!