【发布时间】:2019-04-11 15:22:38
【问题描述】:
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"
}
]
}
}
我的资源实例
SomeResource 类扩展了 JsonResource { 公共函数 toArray($request) { 返回 [ '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, ]; } }我的集合实例:
类 SomeCollection 扩展 ResourceCollection { 公共 $collects = 'App\Http\Resources\SomeResource'; 公共函数 toArray($request) { 返回 [ '数据' => $this-> 集合, ]; } }使用基本的雄辩方法
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
];
}
}
一些集合
class SomeCollection extends ResourceCollection
{
public $collects = 'App\Http\Resources\SomeResource';
public function toArray($request)
{
return [
$this->collection,
];
}
}
一些资源
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,
];
}
}
【问题讨论】:
-
您在“喜欢此代码”中显示的响应不是正确的 json 响应,您可以尝试使用 return response()->json(['statusCode'=>'1', 'statusMessage'=>'你的消息','Result'=>$variable]);
-
我问的不是这个
-
请详细说明你的问题?
-
我需要按特定列groupBy 我的resource response。
-
请尝试使用 ->groupBy('tableName.atttribute','asc');如果它运行良好,否则尝试使用 DB::raw 查询
标签: php laravel orm eloquent resources