Table consultation with CONCAT and JOIN?

Asked

Viewed 51 times

2

I need to get a collection as a result of consultation on 3 tables using concat and join, the image below shows the relationship between them:

tabelas do banco

I tried using the code below

$teste = DB::table('clientes as c')
      ->leftjoin('reservas as r', 'r.codReserva', '=', 'b.ce_denunciacrime')
      ->leftjoin('produtos as p', 'p.codProduto', '=', 'r.codReserva')
      ->select('p.codProduto','r.codReserva',
                DB::raw("CONCAT(c.codCliente,', ') as codCliente"))
      ->limit(1)
      ->get();

dd($teste);

the array result should be something like this:

#items: array:1[
0 => {#498 
  +"codProduto": 1
  +"codReserva": 2
  +"codCliente": 20,30,40
}]

Imagine this table below, the result would be the first two columns plus the concatenation of the values of the third, resulting in the array shown above.

<table border=1>
<tr>
<th>codProduto</th><th>codReserva</th><th>codCliente</th>
<tr>
<td>1</td><td>2</td><td>20</td>
</tr>
<tr>
<td>2</td><td>2</td><td>30</td>
</tr>
<tr>
<td>3</td><td>2</td><td>40</td>
</tr>
  • The codCliente gathers all the numbers!? Explain better.

  • that. the codClient column would be: "20,30,40"...

1 answer

3

I was able to solve using 'GROUP_CONCAT' as in the query below:

$teste = DB::table('clientes as c')
    ->leftjoin('reservas as r', 'r.codReserva', '=', 'b.ce_denunciacrime')
    ->leftjoin('produtos as p', 'p.codProduto', '=', 'r.codReserva')
    ->select('p.codProduto','r.codReserva',
              DB::raw("GROUP_CONCAT(c.codCliente,'') as codCliente"))
    ->limit(1)
    ->groupBy('p.codProduto','r.codReserva')
    ->get();

dd($teste);

Browser other questions tagged

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