在CakePHP中找到结果冗余MODELNAME [英] Redundant ModelName in CakePHP find Results
问题描述
我试图摆脱由CakePHP的find方法返回的结果数组中的多余的型号名称。因为它是现在,如果我做类似$结果= $这个 - >型号 - >找到('所有'),我会用$结果[产品型号] [字段名],而不是$结果访问结果字段[字段名]。
I am trying to get rid of the redundant model names in the results array returned by the find method in CakePHP. As it is now, if I were to do something like $results = $this->Model->find('all'), I would have to access a result field by $results[Model][fieldName] instead of $results[fieldName].
据我所知,在数组型号名称中具有优势,但我想建立一个API,所以我需要JSON EN code数组。随着包括型号名称,我得到喜欢的东西可怕的:
I understand that having the model name in the array has benefits but I am trying to build an api so I need to json encode the array. With the model name included I get something hideous like:
[{"Model":{"field":"blah","field":"blah"}},{"Model":{"field":"blah","field":"blah"}}]
我想要的东西更优雅,如:
I want something more elegant like:
[{"field":"blah","field":"blah"},{"field":"blah","field":"blah"}]
任何想法?
推荐答案
在你的控制器,而不是序列化的查找结果,连载更深一层。
In your controller, instead of serializing the results of the find, serialise a level deeper.
假设CakePHP的2:
Assuming CakePHP 2:
$things = $this->Thing->find('all');
$things = Set::extract('/Thing/.', $things);
现在您的结果应该是免费的在你的JSON额外级别的。
Now your results should be free of the extra level in your JSON.
另一种方法,这样做是 for循环的冗长方式
在结果:
The alternative, lengthy way of doing it is to for loop
over the results:
foreach ($things as $k => &$v) {
$v = $v['Thing']
}
在这之后,你的$事情会已删除键的额外级别。
After that, your $things will have removed the extra level of keys.
这篇关于在CakePHP中找到结果冗余MODELNAME的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!