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

时间:2018-08-21 09:03:23

标签: laravel eloquent

以下代码:

$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 个答案:

答案 0 :(得分:1)

如果要获取数据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();

答案 1 :(得分:0)

是的,由于orWhere语句可能会导致问题。

在您的情况下,如果没有succcessfully_created顺序,那么查询将搜索一条符合其余orWhere语句之一的记录。

因此,您可以获得全部或几乎所有的订单。

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

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