我有两张 table 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"
}
}
]
最佳答案
您无法更改 Eloquent 返回关系集合的方式,也不应该更改,但您当然可以在响应中操作集合:
$model->post_metas->pluck('value', 'key');
阅读所有可用的 collection methods .
关于php - Laravel Eloquent 在单个键值对中获取所有内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53107934/