我有两个表posts
和post_metas
,其架构如下:
POSTS
+------------+------------------+
| Field | Type |
+------------+------------------+
| id | int(10) unsigned |
| title | varchar(255) |
| content | longtext |
POST_METAS
+------------+------------------+
| Field | Type |
+------------+------------------+
| id | int(10) unsigned |
| post_id | int(10) unsigned |
| key | varchar(255) |
| value | longtext |
使用简单的一对多关系,我得到此输出
[
{
"id": 1,
"title": "Dibbert LLC",
"content": null,
"post_metas": [
{
"key": "code",
"value": "YSRSLBZ7"
},
{
"key": "agent_id",
"value": "32"
}
]
}
]
我想知道是否可以将post metas作为一个对象而不是数组,像这样:
[
{
"id": 1,
"title": "Dibbert LLC",
"content": null,
"post_metas": {
"code": "YSRSLBZ7",
"agent_id": "32"
}
}
]
答案 0 :(得分:4)
您不能更改Eloquent返回关系集合的方式,也不想更改,但是您可以肯定地在响应中操纵该集合:
$model->post_metas->pluck('value', 'key');
阅读所有可用的collection methods。
答案 1 :(得分:0)
默认情况下,Laravel返回Collection类的实例。查询关系元素时也将应用此方法。
现在,如果要自定义要返回的字段(例如,隐藏,转换或添加某些内容),则可以使用API Resources。这将使您轻松地转换响应。
选中this other answer可以帮助您使用API资源。
要实现API资源来满足您的需求,我们需要:
php artisan make:resource PostMetaResource
php artisan make:resource PostResource
App / Http / Resources / PostMetaResource.php
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\Resource;
class PostMetaResource extends Resource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request
* @return array
*/
public function toArray($request)
{
return [
'key' => $this->key,
'value' => $this->value,
];
}
}
App / Http / Resources / PostResource.php
class PostResource extends Resource
{
use PostMetaResource;
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->title,
// the rest of your fields..
// here is where we load the relationship resource:
'post_metas' => PostMetaResource::collection($this->whenLoaded('post_metas')),
];
}
}
use App\Http\Resources\PostResource;
//
public function index(Request $request)
{
$posts = Post::with('post_metas')->get();
return PostResource::collection($posts);
}