0

如何使用查询生成器或 eloquent 重现下面的这个 sql 语句?我试过使用 DB::raw... 和 join('something', function ($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
4

1 回答 1

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();
于 2013-07-25T08:48:28.507 回答