如何重命名cakephp中的json数组名?
How to rename the json array name in cakephp?
我想更改以下代码的 json 名称
例如
{
"id": 1,
"mb_item_list": {
"item_name": "Something"
}
}
将代码更改为
{
"id": 1,
"name": "Something"
}
这里分享控制器代码
if ($this->request->is('get')) {
$itemname= $this->request->query('item_name');
$searchitem = $this->MbPriceList->find('all')
->contain(['MbItemList' => function ($q) {
return $q->select(['item_name']);
}])
->select(['MbItemList.item_name', 'id']);
$this->set([
'response' => $searchitem,
'_serialize' => ['response']
]);
}
我认为您可以在查找器选项中使用 fields
。
Fields
允许我们为数据库字段生成别名并有助于避免嵌套数组:
$searchitem = $this->ModelA->find('all' , [
'fields' => [
'id',
'name' => 't1.whatever'
],
'join' => [
'table' => 'model_b',
'alias' => 't1',
'type' => 'INNER',
'conditions' => [
't1.id = ModelA.id'
]
]
])
->toArray();
使用此方法生成的示例输出:
[
{
"id":1,
"name":"Config"
},
{
"id":2,
"name":"Dashboard"
},
{
"id":3,
"name":"Files"
}
]
我想更改以下代码的 json 名称
例如
{
"id": 1,
"mb_item_list": {
"item_name": "Something"
}
}
将代码更改为
{
"id": 1,
"name": "Something"
}
这里分享控制器代码
if ($this->request->is('get')) {
$itemname= $this->request->query('item_name');
$searchitem = $this->MbPriceList->find('all')
->contain(['MbItemList' => function ($q) {
return $q->select(['item_name']);
}])
->select(['MbItemList.item_name', 'id']);
$this->set([
'response' => $searchitem,
'_serialize' => ['response']
]);
}
我认为您可以在查找器选项中使用 fields
。
Fields
允许我们为数据库字段生成别名并有助于避免嵌套数组:
$searchitem = $this->ModelA->find('all' , [
'fields' => [
'id',
'name' => 't1.whatever'
],
'join' => [
'table' => 'model_b',
'alias' => 't1',
'type' => 'INNER',
'conditions' => [
't1.id = ModelA.id'
]
]
])
->toArray();
使用此方法生成的示例输出:
[
{
"id":1,
"name":"Config"
},
{
"id":2,
"name":"Dashboard"
},
{
"id":3,
"name":"Files"
}
]