如何在laravel中正确使用orWhere?

时间:2015-06-08 07:14:08

标签: php mysql laravel-5

我想在laravel elequent中进行以下查询

select from table where cond1 and(cond or cond or cond..)and cond3.

我使用了以下代码,

$invoice = Invoice::with("items", "salesPerson", "client");
if ($q = Request::input("q")) {
        $invoice->where("invoices.invoice_number", 'LIKE', "%$q%");
        $invoice->orWhere("invoices.reference_number", 'LIKE', "%$q%");
        $invoice->orWhere("invoices.client_name", 'LIKE', "%$q%");
        $invoice->orWhere("invoices.invoice_date", 'LIKE', "$q%");
        $invoice->orWhere("invoices.due_date", 'LIKE', "$q%");
    }
$invoice->whereNull("invoices.deleted_at");

但它也会返回已删除的记录。如何修复此问题?

1 个答案:

答案 0 :(得分:1)

在这种情况下,nested where会派上用场:

$invoice = Invoice::with("items", "salesPerson", "client");
if ($q = Request::input("q")) {
    $invoice->where(function($query) use ($q){
        $query->where("invoices.invoice_number", 'LIKE', "%$q%");
        $query->orWhere("invoices.reference_number", 'LIKE', "%$q%");
        $query->orWhere("invoices.client_name", 'LIKE', "%$q%");
        $query->orWhere("invoices.invoice_date", 'LIKE', "$q%");
        $query->orWhere("invoices.due_date", 'LIKE', "$q%");
    });
}
$invoice->whereNull("invoices.deleted_at");