Laravel查询生成器:CONCAT和JOIN

时间:2018-07-10 10:42:30

标签: laravel join concat

我有一个数据库,如下图,其中有三个表:

[表格] [1]

https://i.stack.imgur.com/G947f.jpg

我需要实现如下表的查询:

<table border=1>
<tr>
<th>codProduto</th><th>codReserva</th><th>codClientes</th>
</tr>
<tr>
<td>1</td><td>2</td><td>20,30,40</td>
</tr>
</table>

我试图做这样的事情:

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

有人可以帮我实现吗?非常感谢。我下面有这样的东西

array:3[ 
0 => {#498 
  +"codProduto": 1
  +"codreserva": 2
  +"codCiente": 20,
}]
1 => {#498 
  +"codProduto": 1
  +"codreserva": 2
  +"codCiente": 30,
}] 
2 => {#498 
  +"codProduto": 1
  +"codreserva": 2
  +"codCiente": 40,
}]

但是我想得到:

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

1 个答案:

答案 0 :(得分:0)

仅使用group_concat更改查询,如下所示:

$test = 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();