1

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

2

4 Answers 4

2

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();
Sign up to request clarification or add additional context in comments.

2 Comments

Hi, thanks...the result is [{"total_record":1}]...I would like to have 1 instead.
@user10087184 try second way
0
$total_record = DB::table('player_games')->where('team_score', '<', 'rival_score')
                         ->count();

Comments

0

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

Comments

0

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.

1 Comment

There is a built-in to avoid the dirty hack with backticks (which is not DBMS agnostic by the way): $query->whereColumn('left_column', '<', 'right_column')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.