在laravel中左边连接子查询

时间:2013-06-04 19:04:05

标签: left-join aggregate laravel-4 eloquent query-builder

如何使用查询构建器或eloquent重现下面的sql语句?我已经尝试过使用DB :: raw ...并加入('某事',函数($ join)......但它不起作用。如果有人知道如何解决这个问题,请给我一个例子。

SELECT
musica.titulo,
p.qtd_pedidos,
a.qtd_avaliacoes,
a.media_avaliacoes
FROM
musica
LEFT JOIN (
    SELECT musica_id, COUNT(pedido.id) as qtd_pedidos
    FROM pedido GROUP BY pedido.musica_id
) as p ON p.musica_id = musica.id
LEFT JOIN (
    SELECT musica_id, COUNT(avaliacao.id) as qtd_avaliacoes,
    ROUND(AVG(avaliacao.nota),1) as media_avaliacoes
    FROM avaliacao GROUP BY avaliacao.musica_id
) as a ON a.musica_id = musica.id

1 个答案:

答案 0 :(得分:1)

假设您描述了Musica,Pedido和Avaliacao模型及其关系:

Musica::with(
    array('pedido' => function($query) {
              $query->select(DB::raw('musica_id, COUNT(pedido.id) as qtd_pedidos'))
                    ->groupBy('musica_id');
          },
          'avaliacao' => function($query) {
              $query->select(DB::raw(
                                'musica_id, '
                              . 'COUNT(avaliacao.id) as qtd_avaliacoes, '
                              . 'ROUND(AVG(avaliacao.nota),1) as media_avaliacoes'
                            ))
                    ->groupBy('musica_id');
          }
    )
)->get();