Select with JOIN to return an Object with Internal List

Asked

Viewed 172 times

0

I wonder if it is possible to select with Join where the second table will return more than one row and in that create an object with an internal list. For clarity see the example:

Tabela Usuario: idUsuario, nome, cpf
Tabela Veiculos: idVeiculo, nome, placa, dono

select: select u.nome, v.placa from Usuario u JOIN Veiculos v ON v.dono = u.idUsuario;

resultado:
joao, kkk-0000
joao, jjj-0000
paulo, iii-9999
paulo, yyy-9999

In PDO I use the PDO command::FETCH_CLASS and receive the following Object.

Objetoconsulta:

obj[0] = joao, kkk-0000
obj[1] = joao, jjj-0000
obj[2] = paulo, iii-9999
obj[3] = paulo, yyy-9999 

I would like to receive this way:

obj[0] = joao, array(kkk-0000,jjj-0000)
obj[1] = paulo, array(iii-9999, yyy-9999) 

1 answer

0


If you use:

$Ps->fetchAll(PDO::FETCH_COLUMN|PDO::FETCH_GROUP);

Will get:

array(2) {
    ["joao"]=>
        array(2) {
            [0]=>
            string(8) "kkk-0000"
            [1]=>
            string(8) "jjj-0000"
        }
    ["paulo"]=>
        array(2) {
            [0]=>
            string(8) "iii-9999"
            [1]=>
            string(8) "yyy-9999"
        }
}

I have no way to test it now, but maybe with the others modes of fetch you can also get an object instead of an array.

  • 1

    Thank you very much, it helped me a lot. I used it as follows:$Ps->fetchAll(PDO::FETCH_GROUP);

Browser other questions tagged

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