Laravel 查询不允许我查询 and where inside orWhere
Laravel query isn't allowing me to query and where inside orWhere
我有 laravel 和 laravel-livewire。也许这有点矫枉过正,但我想将结果限制在 10 个左右,然后在用户输入姓名或 phone 数字时将这 10 个结果过滤为新结果。如果我只使用其中一个语句,查询工作得很好。如果我去掉 phone 并保留名称,它会起作用,删除名称并保留 phone 也是如此。但是,如果我同时拥有下面的两者,那将不起作用。在调试栏中,我看到了查询,它看起来像它应该的那样,但是一旦我开始输入,我就没有得到任何结果。
$customers = DB::table('customers')->where('user_id', auth()->id())
->where(function($query) {
$query->where('phone', 'like', '%'.$this->phone.'%')
->orWhere('name', 'like', '%'.$this->name.'%');
})
->limit(10)
->get();
在调试栏中输出查询
select *
from `customers`
where `user_id` = 12
and (`phone` like '%%' or `name` like '%%')
limit 10`
你可以这样试试
$customers = DB::table('customers')->where('user_id', auth()->id())
->where(function($query) {
$query->when(!is_null($this->phone), function ($q) {
$q->where('phone', 'like', '%'.$this->phone.'%')
})
->when(!is_null($this->name), function ($q) {
$q->where('name', 'like', '%'.$this->name.'%')
});
})
->limit(10)
->get();
我有 laravel 和 laravel-livewire。也许这有点矫枉过正,但我想将结果限制在 10 个左右,然后在用户输入姓名或 phone 数字时将这 10 个结果过滤为新结果。如果我只使用其中一个语句,查询工作得很好。如果我去掉 phone 并保留名称,它会起作用,删除名称并保留 phone 也是如此。但是,如果我同时拥有下面的两者,那将不起作用。在调试栏中,我看到了查询,它看起来像它应该的那样,但是一旦我开始输入,我就没有得到任何结果。
$customers = DB::table('customers')->where('user_id', auth()->id())
->where(function($query) {
$query->where('phone', 'like', '%'.$this->phone.'%')
->orWhere('name', 'like', '%'.$this->name.'%');
})
->limit(10)
->get();
在调试栏中输出查询
select *
from `customers`
where `user_id` = 12
and (`phone` like '%%' or `name` like '%%')
limit 10`
你可以这样试试
$customers = DB::table('customers')->where('user_id', auth()->id())
->where(function($query) {
$query->when(!is_null($this->phone), function ($q) {
$q->where('phone', 'like', '%'.$this->phone.'%')
})
->when(!is_null($this->name), function ($q) {
$q->where('name', 'like', '%'.$this->name.'%')
});
})
->limit(10)
->get();