我是Laravel的新手。我正在制作一个应用来对电视节目的播出时间进行评分。我想获取每个季节的信息,包括平均评分和当前用户的个人评分。

目前,我只是使用原始MySQL进行访问。

$seasons = \DB::select('

SELECT * FROM seasons

LEFT JOIN (SELECT season_id, AVG(rating) as avg_rating FROM ratings_season
GROUP BY season_id) t2 ON seasons.id = t2.season_id

LEFT JOIN (SELECT season_id, rating FROM ratings_season WHERE user_id = 1) t3 ON seasons.id = t3.season_id

ORDER BY seasons.number DESC');


如何使用Laravel Relationships将原始查询转换为原始查询?

最佳答案

尝试根据自己的喜好修改此代码

DB::table('seasons')
->select('*')
->leftJoin(
    DB::raw('(SELECT season_id, AVG(rating) as avg_rating FROM ratings_season GROUP BY (season_id)
    ) as t2'), function ($join) {
        $join->on ( 'seasons.id', '=', 't2.season_id' );
    }
)
->leftJoin(
    DB::raw('(SELECT season_id, rating FROM ratings_season WHERE user_id = 1) as t3'), function ($join) {
        $join->on ( 'seasons.id', '=', 't3.season_id' );
    }
)
->orderBy('seasons.number', 'desc')
->get();

关于mysql - Laravel 5.3如何进行多个联接,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41684550/

10-12 12:53