简体   繁体   English

使用Laravel查询生成器转换MySQL查询

[英]Convert MySQL query using Laravel Query Builder

I have a question regarding a MySQL query. 我有一个关于MySQL查询的问题。
I would like to know how to create the same query using Laravel QUERY Builder 我想知道如何使用Laravel QUERY Builder创建相同的查询

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

Thanks 谢谢

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();
$total_record = DB::table('player_games')->where('team_score', '<', 'rival_score')
                         ->count();

in Laravel Query Builder you can write this: 在Laravel查询生成器中,您可以编写以下代码:

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

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

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. 之所以需要\\DB::raw是因为,如果不需要,则where的右侧将被自动假定为一个值并作为绑定传递,但是您需要将其作为原始传递DB表达式,表明它实际上是列名。 The backticks are added because it's good to escape the column names. 添加反引号是因为最好对列名进行转义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM