Skip to content
Advertisement

Laravel joining tables in a database query

I have this code:

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

It displays the amount of income, but i need to display this information only if the user id indicated in the winner_id column in games table. That is, how can I connect another table in this query?

Advertisement

Answer

You don’t need join here, exists will be enough. I guess you have game_id column in bets table.

$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');
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement