gpt4 book ai didi

mysql - Laravel 5.3 如何进行多重连接

转载 作者:行者123 更新时间:2023-11-30 22:06:11 24 4
gpt4 key购买 nike

我是 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 关系将此原始查询转换为原始查询?

最佳答案

尝试根据自己的喜好调整此代码

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com