Error converting to vector (->toArray()) in Cakephp

Asked

Viewed 54 times

0

Good night.

I’m creating a file function 'src/Model/Table/ProdutosTable.php', using version 3 of Cakephp. The function must return information in a vector of a list of products according to the date selected. The problem is that when converting the result of 'Query' to an array, it becomes empty, not giving continuity to the logic of the code. Could someone please help me?

Below follows the code:

src/Model/Table/ProdutosTable.php

//Função para retornar uma lista de produtos.
public function lista($data = null) {
    //Variáveis
    $produtos_model = $this;
    $dados = [];
    $lista_produtos = [];

    //Formata a data.
    $data = new Time($data);
    $data = $data->format('Y-m-d');

    //Seleciona todos os produtos no banco de dados de acordo com os parâmetros passados.
    $query = produtos_model->find()
        ->where(['data' => $data]);

    //Converte o resultado para um array.
    $produtos = $query->toArray(); //Aqui ele deveria realizar a conversão, mas isto não acontece.//

    //Cria a lista com os dados necessarios.
    foreach($produtos as $produto) {
        $dados = [
            'id' => $produto->id,
            'nome' => $produto->nome,
            'referencia' = $produto->referencia
        ];

        array_push($lista_produtos, $dados);
    }

    //Retorna os dados.
    return $lista_produtos;
};
  • give a var_dump() in $query and $produtos

2 answers

0

If you want to get a group nested result,

In this passage

    $query = produtos_model->find()
        ->where(['data' => $data]);

    //Converte o resultado para um array.
    $produtos = $query->toArray(); //Aqui ele deveria realizar a conversão, mas isto não acontece.//

    //Cria a lista com os dados necessarios.
    foreach($produtos as $produto) {
        $dados = [
            'id' => $produto->id,
            'nome' => $produto->nome,
            'referencia' = $produto->referencia
        ];

        array_push($lista_produtos, $dados);
    }

Modify to

    $query = produtos_model->find('list',
        [
            'keyField' => 'nome',
            'valueField' => 'referencia',
            'groupField' => 'id',
        ]
    )
        ->where(['data' => $data]);

    //Converte o resultado para um array.
    $produtos = $query->toArray();

But it is not clear what the purpose of use is, as there are different options for each purpose.

Maybe instead of list, you want to use threaded.

See the examples in the manual http://book.cakephp.org/3.0/en/retrieving-data-and-resultsets.html#finding-key-value-pairs

  • Good morning @Danielomine. The problem is that if I comment on this line "//$products = $query->toArray();" and return the $query variable, it returns the objects of my request at find(). But if I take the comment again, the product variable is returned empty ([ ]). Note: I am using Cakephp 3’s debug() method to check the function’s internal return state.

0


First of all I would like to thank @Danielomine again, who is helping me here at Stack Overflow. And I would like to apologize, because I accidentally posted the code already with the solution of the problem. That’s right, the code that heads this topic already has the bug fixed. Again I’m sorry. When I wrote the code here on Overflow I didn’t copy it from my development environment and paste it here (because I was out of it). In fact I rewrote the function here, and when I did, I rewrote it with the solution of the problem, without realizing.

The problem of this question was in the variable '$data'. This variable is passed from a ". json" request to the controller "ProdutosController.php". For the sake of organization, I’m putting the functions that access the database (Except the basic functions of cake like index(), add(), Edit(), delete()...) in the file quoted at the beginning of the post (src/Model/Table/ProdutosTable.php).

The point was that in the file "ProdutosController.php" I already converted this date to an object of type "Time" ($data = new Time($data);), but did not apply the format function (->format('Y-m-d');) in it. Then this variable was passed to the list function (src/Model/Table/ProdutosTable.php) with the following content:

object(Cake\I18n\Time) {
    'time' => '2016-09-22T00:00:00+00:00',
    'timezone' => 'UTC',
    'fixedNowTime' => false
},

When it should be passed this way:

2016-09-22

So when I rewrote the function here at Overflow with the excerpt:

//Formata a data.
$data = new Time($data);
$data = $data->format('Y-m-d');

This had already solved the problem ;)

Finally, I can’t explain why the conversion to a vector (->toArray();) was not performed, but when performing the format in the variable $data the problem has been solved. Again I apologize for the failure. And many thanks to the entire Overflow community.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.