【问题标题】:Laravel query isn't allowing me to query and where inside orWhereLaravel 查询不允许我查询内部的位置或位置
【发布时间】:2021-09-02 18:39:23
【问题描述】:

我有 laravel 和 laravel-livewire。也许这有点矫枉过正,但我​​想将结果限制在 10 个左右,然后当人们输入姓名或电话号码时,让这 10 个结果过滤到新结果。如果我只使用其中一个语句,查询就可以正常工作。如果我摆脱电话并留下姓名,它会起作用,摆脱姓名并留下电话也是如此。但是,如果我有两个都喜欢下面它不起作用。在调试栏中,我看到了查询,它看起来应该是这样,但是一旦我开始输入,我就没有得到任何结果。

$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`

【问题讨论】:

  • $this->phone$this->name 都可以有值吗?
  • 尝试在查询之前检查“$this”是否有值。并确保“$this”中同时包含电话和姓名。如果 $this 存在并且有值,那么也许你可以尝试这样的测试: $that = $this ...... ->where(function($query) use ($that) {
  • 两个变量都可以有值,事实上它们最终都不可能有。他们俩的值都更新得很好,@kenyalang 的回答解决了这个问题。谢谢!

标签: laravel eloquent laravel-livewire


【解决方案1】:

你可以试试这样

$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();

【讨论】:

    猜你喜欢
    • 2012-10-26
    • 2015-09-17
    • 2018-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-08
    相关资源
    最近更新 更多