Return json 模型中的自定义阵列与 Lumen
Return custom array in json model with Lumen
使用 Lumen 8 我有:
- 型号:商店
- 控制器:存储控制器
- 存储库:存储库
我可以毫无问题地得到我的 Store
并得到下面的 json :
{
"id_store": 1,
"name": "Abcde",
"email": "",
"phone": "0123456789"
}
我想获取 Store
的 open/close 时间。在我的模型中,我有一个数组(用于测试),我可以这样显示它:
return response()->json(['item' => $store, 'time' => $store->getTime()], 200);
得到这个结果:
{
"item": {
"id_store": 1,
"name": "Abcde",
"email": "",
"phone": "0123456789"
},
"time": {
"1": "January",
"2": "February",
"3": "March"
}
}
问题是我现在有 2 个部分。我如何才能在我的商店价值中拥有这个数组?如下所示:
{
"id_store": 1,
"name": "Abcde",
"email": "",
"phone": "0123456789"
"time": {
"1": "January",
"2": "February",
"3": "March"
}
}
看错了,在Laravel,你可以使用资源 API 资源,我想在 Lumen 没有,更多文档在这里:https://laravel.com/docs/8.x/eloquent-resources
在您的资源中,只需包含类似内容:
public function toArray($request)
{
return [
'id_store' => $this->id_store,
'name' => $this->name,
'email' => $this->email,
'phone' => $this->phone,
'time' => $this->->getTime(),
];
}
或者只是 return 这样的事情:
$store->time = $store->getTime();
return response()->json($store, 404);
顺便说一句,为什么是 404?
使用 Lumen 8 我有:
- 型号:商店
- 控制器:存储控制器
- 存储库:存储库
我可以毫无问题地得到我的 Store
并得到下面的 json :
{
"id_store": 1,
"name": "Abcde",
"email": "",
"phone": "0123456789"
}
我想获取 Store
的 open/close 时间。在我的模型中,我有一个数组(用于测试),我可以这样显示它:
return response()->json(['item' => $store, 'time' => $store->getTime()], 200);
得到这个结果:
{
"item": {
"id_store": 1,
"name": "Abcde",
"email": "",
"phone": "0123456789"
},
"time": {
"1": "January",
"2": "February",
"3": "March"
}
}
问题是我现在有 2 个部分。我如何才能在我的商店价值中拥有这个数组?如下所示:
{
"id_store": 1,
"name": "Abcde",
"email": "",
"phone": "0123456789"
"time": {
"1": "January",
"2": "February",
"3": "March"
}
}
看错了,在Laravel,你可以使用资源 API 资源,我想在 Lumen 没有,更多文档在这里:https://laravel.com/docs/8.x/eloquent-resources
在您的资源中,只需包含类似内容:
public function toArray($request)
{
return [
'id_store' => $this->id_store,
'name' => $this->name,
'email' => $this->email,
'phone' => $this->phone,
'time' => $this->->getTime(),
];
}
或者只是 return 这样的事情:
$store->time = $store->getTime();
return response()->json($store, 404);
顺便说一句,为什么是 404?