1
I’m generating a json from a find in Cakephp.
Controller:
public function listar() {
$this->layout = 'ajax';
$this->set('resultados', $this->Sala->listarSala());
}
Model:
public function listarSala() {
$options = array(
'fields' => array(
'Sala.id', 'Sala.nome', 'Sala.data', 'Sala.inicio', 'Sala.fim'
),
'conditions' => array(
'Sala.data >= curdate()',
),
'order' => array(
'Sala.data ASC',
'Sala.inicio ASC'
),
'limit' => 50
);
return $this->find('all', $options);
}
View:
<?php
echo json_encode($resultados);
But when I visualize the answer, I get the following result:
[
{"Sala":{"id":"47","nome":"Grupo","data":"15\/05\/2014","inicio":"09:30:00","fim":"11:00:00"}},
{"Sala":{"id":"48","nome":"Grupo","data":"29\/05\/2014","inicio":"09:30:00","fim":"11:00:00"}},
{"Sala":{"id":"49","nome":"Grupo","data":"12\/06\/2014","inicio":"09:30:00","fim":"11:00:00"}}
]
I noticed that it creates a room(model) object and inside it the properties searched in Mysql.
My question is the following, how could I make Cakephp return this result without the room object, with the normal json notation, or would that be so? What would be the right way?
This way it worked:
<?php
foreach ($resultados as $sala) {
 $salas[] = $sala["Sala"];
}
echo json_encode($salas);
– Marcelo Aymone
But that’s not exactly what I intended, I wanted a way that this result already came from cake.
– Marcelo Aymone
"Room" in cake represents the model you are using and the normal is that it always tells you that, part of the framework conventions. This helps in future code maintenance
– Erlon Charles