Ad

Laravel Joining Tables In A Database Query

- 1 answer

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?

Ad

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');
Ad
source: stackoverflow.com
Ad