Php 在数据库查询中连接表的LAVEL

Php 在数据库查询中连接表的LAVEL,php,mysql,laravel,laravel-query-builder,Php,Mysql,Laravel,Laravel Query Builder,我有以下代码: $classic_games_money = DB::table('bets') ->where('user_id', $this->user->id) ->sum('price'); 它显示收入金额,但仅当games表中winner\u id列中指示的用户id时,我才需要显示此信息。也就是说,如何连接此查询中的另一个表?您不需要在这里加入,存在就足够了。我猜您在bets表中有game\u id列 $classic_games_money

我有以下代码:

$classic_games_money = DB::table('bets')
    ->where('user_id', $this->user->id)
    ->sum('price');

它显示收入金额,但仅当
games
表中
winner\u id
列中指示的用户id时,我才需要显示此信息。也就是说,如何连接此查询中的另一个表?

您不需要在这里加入
存在
就足够了。我猜您在
bets
表中有
game\u id

$classic_games_money = DB::table('bets')
    ->where('user_id', $this->user->id)
    ->whereExists(function ($query) {
        $query
            ->selectRaw(1)
            ->from('games')
            ->whereRaw('games.id = bets.game_id')
            ->whereRaw('games.winner_id = bets.user_id');
    })
    ->sum('price');

你需要在这里提供更多的细节。
游戏
用户
下注
模型之间的关系是什么?是的,都很好。但是你能描述一下我,selectRaw(1)
是什么意思吗?它的意思是这样的:我们不需要选择任何列来实现exists函数,我们有1,这足以让exists取消对行的响应。对不起,我的无礼,但你能回答另一个问题吗?它与同一个问题有关,但有一个稍微不同的解决方案。我将不胜感激