mysql - 我想检查我的 sql 命令是否包含输入的数据

标签 mysql laravel laravel-5

我有两轮“第一轮和淘汰赛”。只有在第一轮获得最高分的第 4 支球队才能进入淘汰赛。现在首先,我想从第一轮中选择那 4 支球队,然后检查输入的球队是否在选定的 4 支球队中。看看我的代码(到目前为止我试过了) [在这张图片中,标记的两支球队应该被排除在外,但当我给出条件时,它不会排除那两支球队]

enter image description here

$matches= new Match();
$matches->team1 = $request->input('team1');
$matches->team2 = $request->input('team2');

$ko =  DB::select('SELECT * FROM points WHERE round="first" ORDER BY points DESC , run_rate DESC LIMIT 4');

if($ko == $matches->team1 || $ko == $matches->team2) {
    $matches->round = "ko";
} else {
   $matches->round = "first";   
}

$kos 更新后的截图。 enter image description here

最佳答案

首先,$ko 不包含查询结果,直到您向它传递一个闭包,在本例中为 ->first()

$ko =  DB::select('SELECT * FROM points WHERE round="first" ORDER BY points DESC , run_rate DESC LIMIT 4')->first();

接下来,您需要将 $ko->team 的值与 $matches->team1$matches->team2 进行比较:

if($ko->team == $matches->team1 || $ko->team == $matches->team2) {
  ...
}

最后,一些清理工作。数据库查询可以简化为使用 Eloquent 语法,而不是原始的 SELECT:

$ko = DB::table("points")
->where("round", "=", "first")
->orderBy("points", "DESC")
->orderBy("run_rate", "DESC")
// ->limit(4) // Removing this; incompatible with `->first()`
->first();

还有一个逻辑错误;如果你需要limit(4),那么你不能使用->first(),你必须使用->get(),然后创建一个 Collection,它不能与 $matches 进行比较,除非你循环:

$kos = DB::table("points")...->get();

$matches->round = "first";
foreach($kos AS $ko){
    if($ko->team == $matches->team1 || $ko->team == $matches->team2) {
        $matches->round = "ko";
        break;
    }
}

总而言之,您需要重新检查您正在尝试做的事情并阅读 Eloquent 语法、如何执行查询和返回结果、如何循环、访问属性和比较这些结果等。

编辑:因为你在循环和比较,将 $matches->round 的默认值设置为“first”,然后,在循环时,如果比较条件为 true,覆盖 $matches->round 为“ko”并跳出循环。

关于mysql - 我想检查我的 sql 命令是否包含输入的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55378744/

相关文章:

php - MYSQL限制不一致

mysql - 根据条件计算另一个表的总结果减去原始表列的数字

mysql - 将包含数据的新表包含到现有 Debezium 连接器中

mysql - Laravel 到 MySQL 查询连接计时日志记录

php - 使用 phpleague/oauth2-server 使用刷新 token 创建一个全新的访问 token

laravel - 将 Laravel 多授权用户视为一个独特的用户类

mysql - SQL不返回数据

php - Laravel 8 从 AWS S3 Buckets 下载文件

mysql - Laravel 5.1 - 连接到 MySQL 数据库 (MAMP)

javascript - 如何链接外部Js文件中的公共(public)目录