user10087184
user10087184

Reputation: 57

Convert MySQL query using Laravel Query Builder

I have a question regarding a MySQL query.
I would like to know how to create the same query using Laravel QUERY Builder

SELECT count( * ) as total_record FROM `player_games` WHERE team_score <  rival_score

Thanks

Upvotes: 1

Views: 149

Answers (4)

apokryfos
apokryfos

Reputation: 40683

There's a subtle thing here that you need to be aware of:

DB::table('player_games')
     ->where('team_score','<',\DB::raw('`rival_score`'))
     ->count();

The reason why you need \DB::raw is because if you don't then the right-hand side of the where will be automatically assumed to be a value and be passed as a binding, however you need to pass it as a raw DB expression to indicate that it's actually a column name. The backticks are added because it's good to escape the column names.

Upvotes: 0

Jignesh Joisar
Jignesh Joisar

Reputation: 15115

try this one

$query = "SELECT count( * ) as total_record FROM `player_games` WHERE team_score <  rival_score";

$count = \DB::select(\DB::raw($query));

secod way

DB::table('player_games')->where('team_score','<','rival_score')->count();

Upvotes: 2

DaFois
DaFois

Reputation: 2223

in Laravel Query Builder you can write this:

$player_games = DB::table('player_games')->where('team_score','<', 'rival_score')->count();

Reference: https://laravel.com/docs/5.7/queries

Upvotes: 0

Amitoz Deol
Amitoz Deol

Reputation: 442

$total_record = DB::table('player_games')->where('team_score', '<', 'rival_score')
                         ->count();

Upvotes: 0

Related Questions