我在项目中有Cakephp 3,我正在做api休息以获取JSON来获取移动设备中的数据。 我有两个与外键关联的表,如下所示:
MySql tables
----------------------
Table Tickets:
|id|code|price_id|
Table Prices
|id|price|
----------------------
在TicketsTable CakePHP中:
$this->belongsTo('Prices', [
'foreignKey' => 'price_id',
'joinType' => 'INNER'
]);
在我做REST api的控制器中:
$this->loadModel('Tickets');
$entradas = $this-> Tickets->find('all')
->contain('Prices')
->select(['Tickets.code','Prices.price'])
->limit('200')
->toArray();
然后这个解析为JSON的数组返回:
"result":{
"tickets":[
{
"code":"08998112773",
"prices":{
"prices.price":1
}
},
{
"code":"07615265880",
"prices.prices":{ .........
我想要返回这个JSON:
"result":{
"tickets":[
{
"code":"08998112773",
"price":1
},
{
"code":"07615265880",
"price":1 .........
也就是说,价格不会插入到新数组中,并且表的名称不会出现在字段名称中。
非常感谢!!!!
答案 0 :(得分:1)
您可以使用Cake\Collection\Collection::map()来创建新数组:
$tickets = [
'result' => [
'tickets' => [
[
'code' => '123',
'prices' => [
'prices.price' => '2'
]
],
[
'code' => '312423',
'prices' => [
'prices.price' => '4'
]
]
]
]
];
$collection = new Collection($tickets['result']['tickets']);
$new = $collection->map(function ($value, $key) {
return [
'code' => $value['code'],
'price' => $value['prices']['prices.price']
];
});
$result = $new->toArray();
debug(json_encode(['result' => ['tickets' => $new]], JSON_PRETTY_PRINT));
die;
输出结果为:
{
"result": {
"tickets": [
{
"code": "123",
"price": "2"
},
{
"code": "312423",
"price": "4"
}
]
}
}