UPD :已解决。我猜(检查下面的内容)
我正在尝试通过Laravel资源按特定列对我的API响应进行分组
赞
{
"data":{
"1":[ <=== (!!) To have this groups
{
"id":63,
"eve_id":95924195,
"name":"John",
"group":1, <== (!!!) from this column
"is_active":1,
"is_editable":1,
"created_at":"2018-11-08 05:26:20",
"updated_at":"2018-11-08 05:26:20"
},
{
"id":64,
"eve_id":95824961,
"name":"Doe",
"group":1,
"is_active":1,
"is_editable":1,
"created_at":"2018-11-08 05:41:10",
"updated_at":"2018-11-08 05:41:10"
}
]
}
}
我的资源实例
class SomeResource extends JsonResource { public function toArray($request) { return [ 'id' => $this->id, 'name' => $this->name, 'group' => $this->group, 'is_active' => $this->is_active, 'is_editable' => $this->is_editable, 'created_at' => (string) $this->created_at, ]; } }
我的收藏实例:
class SomeCollection extends ResourceCollection { public $collects = 'App\Http\Resources\SomeResource'; public function toArray($request) { return [ 'data' => $this->collection, ]; } }
使用基本的雄辩方法
Some::where('is_active', '1')->get()->groupBy('group');
return ['entries' => $entries];
至少不能解决问题,除非我能以某种方式传递这些条目并在ResourceCollection中对其进行迭代
谢谢。
UPD : 好的,通过创建新的资源实例SomeGroupCollection解决了该问题 和分组来自基本的雄辩方法
$entries = Some::where('is_active', '1')->get()->groupBy('group');
return new SomeGroupCollection($entries);
SomeGroupCollection
class SomeGroupCollection extends ResourceCollection
{
public $collects = 'App\Http\Resources\SomeCollection';
public function toArray($request)
{
return [
'entries' => $this->collection
];
}
}
SomeCollection
class SomeCollection extends ResourceCollection
{
public $collects = 'App\Http\Resources\SomeResource';
public function toArray($request)
{
return [
$this->collection,
];
}
}
SomeResource
class SomeResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'group' => $this->group,
'is_active' => $this->is_active,
'is_editable' => $this->is_editable,
'created_at' => (string) $this->created_at,
];
}
}
答案 0 :(得分:0)
这在 Laravel 8 中对我有用,但是我怀疑它在以前的版本中也一样。
SomeResource::collection($models)->groupBy('group');
但没有data
键。