【问题标题】:I wan to check that is my sql command containing the inputted data or not我想检查我的 sql 命令是否包含输入的数据
【发布时间】:2019-03-27 13:44:54
【问题描述】:

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

$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 更新后的截图。

【问题讨论】:

    标签: mysql laravel laravel-5


    【解决方案1】:

    首先,$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”并中断跳出循环。

    【讨论】:

    • 感谢@Tim Lewis 抽出宝贵时间,但是当我输入的是“$matches->team1=Barisal”和“$matches->team2=Rajshahi”时,$matches->round 应该是"ko" 但它保存为 "first"
    • 你能运行dd($ko) 并告诉我它包含什么吗? (请使用该内容编辑原始问题)
    • 这是我在 dd($kos) 之后得到的结果
    • 是的,看看我的编辑。当您循环和分配时,分配的最后一个值是什么;您可能会在一次迭代中将 $matches->round 分配给“ko”,然后在以后的迭代中将其覆盖为“first”。
    • 是的,我明白了,谢谢兄弟,它救了我的命....也感谢您的宝贵时间
    猜你喜欢
    • 2017-08-04
    • 1970-01-01
    • 1970-01-01
    • 2021-10-26
    • 2011-02-03
    • 2016-05-25
    • 1970-01-01
    • 2021-06-05
    • 2021-09-10
    相关资源
    最近更新 更多