laravel查询构建器查询有什么问题?

时间:2018-10-25 10:53:07

标签: laravel laravel-5.6 laravel-query-builder

我编写了一个查询,使用laravel查询生成器从mysql数据库中获取数据。看看下面给出的查询构建器代码:

$products = DB::table("products as p")
                ->select("p.*")
                ->join("product_tag as pt", "pt.p_id", "p.id")
                ->whereIn("pt.tag_name", function($q1) use($request){
                    $q1->from("user_questionnaire as uc")
                            ->select(DB::raw("distinct(at.prod_tag)"))
                            ->join("questionnaire_answers as qa", function($join){
                                $join->on("qa.question_id", "=", "uc.question_id")
                                        ->where("qa.answer_number", "=", "uc.answer_id");
                            })
                            ->join("answer_tags as at", "at.answer_id", "qa.id")
                            ->where("uc.user_id", $request->user_id);
                })->get();

当我登录此查询生成器时,得到以下响应:

[
    {
        "query": "select `p`.* from `products` as `p` inner join `product_tag` as `pt` on `pt`.`p_id` = `p`.`id` where `pt`.`tag_name` in (select distinct(at.prod_tag) from `user_questionnaire` as `uc` inner join `questionnaire_answers` as `qa` on `qa`.`question_id` = `uc`.`question_id` and `qa`.`answer_number` = ? inner join `answer_tags` as `at` on `at`.`answer_id` = `qa`.`id` where `uc`.`user_id` = ?)",
        "bindings": [
                  "uc.answer_id",
                  115
        ],
        "time": 0.43
    }
]

现在,当我在phpmyadmin中运行此查询时,它将返回所需的结果。但是当print_r $products变量时,它显示空数组([])。

请提出我在查询生成器中做错的事情。

1 个答案:

答案 0 :(得分:0)

您的问题是您正在使用->where()来对最里面的联接应用额外的条件:

->where("qa.answer_number", "=", "uc.answer_id");

在这种情况下,第三个参数作为字符串绑定到查询中,因此您的数据库将把qa.answer_number字段与字符串uc.answer_id进行比较,这可能不是您要查找的内容。当您执行where时,总是将第3个(如果省略运算符则为第2个)添加到查询绑定中,这就是这种行为的结果。

要解决此问题,您应该使用另一个->on(...)向联接添加其他条件:

$join->on("qa.question_id", "=", "uc.question_id")
     ->on("qa.answer_number", "=", "uc.answer_id");

这将确保数据库将列与列进行比较,而不是将列与值进行比较。