代码之家  ›  专栏  ›  技术社区  ›  Aris

查询返回数据库中的所有项

  •  0
  • Aris  · 技术社区  · 6 年前

    以下代码:

    $orders = Order::with([
      "logs"
    ])
    ->where("is_succcessfully_created", true)
    ->orWhere("order_no", "like", "%{$req->search}%")
    ->orWhere("traveler_first_name", "like", "%{$req->search}%")
    ->orWhere("traveler_last_name", "like", "%{$req->search}%")
    ->orWhere("contact_person_first_name", "like", "%{$req->search}%")
    ->orWhere("contact_person_last_name", "like", "%{$req->search}%")
    ->orWhere("contact_person_email", "like", "%{$req->search}%")
    ->orWhere("contact_person_primary_phone", "like", "%{$req->search}%")
    ->orWhere("contact_person_alternate_phone", "like", "%{$req->search}%")
    ->orWhere("return_person_name", "like", "%{$req->search}%")
    ->orWhere("return_person_phone", "like", "%{$req->search}%")
    ->get();
    

    它返回数据库中的所有条目。我雄辩的陈述有什么问题吗?可能是因为哪里吗 ->where("is_succcessfully_created", true) 声明?

    2 回复  |  直到 6 年前
        1
  •  1
  •   James Nguyễn    6 年前

    如果你想得到数据 is_succcessfully_created = true (("order_no", "like", "%{$req->search}%") or ("traveler_first_name", "like", "%{$req->search}%") ...) ,您可以这样写:

    $orders = Order::with([
                "logs"
            ])->where("is_succcessfully_created", true)
                ->where(function ($query) {
                    $query->where("order_no", "like", "%{$req->search}%")
                        ->orWhere("traveler_first_name", "like", "%{$req->search}%")
                        ->orWhere("traveler_last_name", "like", "%{$req->search}%")
                        ->orWhere("contact_person_first_name", "like", "%{$req->search}%")
                        ->orWhere("contact_person_last_name", "like", "%{$req->search}%")
                        ->orWhere("contact_person_email", "like", "%{$req->search}%")
                        ->orWhere("contact_person_primary_phone", "like", "%{$req->search}%")
                        ->orWhere("contact_person_alternate_phone", "like", "%{$req->search}%")
                        ->orWhere("return_person_name", "like", "%{$req->search}%")
                        ->orWhere("return_person_phone", "like", "%{$req->search}%")
                })->get();
    
        2
  •  0
  •   Martin    6 年前

    是的,可能有问题,因为 orWhere 声明。

    在你的情况下,如果没有 succcessfully_created 然后,查询将搜索一条满足其余记录之一的记录。 何处 声明。

    所以你得到 全部或几乎全部 命令的

    您应该将all orwhere语句放入嵌套的where函数中:

    ->where("is_succcessfully_created", true)
    ->orWhere(function($query) {
         ...
         all current orWhere go here 
         ...
    })