【问题标题】:Laravel Eloquent Where and orWhere with Eager Load not working wellLaravel Eloquent Where and or Where with Eager Load 无法正常工作
【发布时间】:2019-09-11 14:08:08
【问题描述】:

我已经用这些表创建了带有急切负载的 JOIN

  1. 交易(transaction_details
  2. Transaction_details(Transaction 的childMutasi_logsparent
  3. Mutasi_logs(transaction_details

然后我添加一些过滤器,例如:

  1. 只显示我的数据(由登录用户创建的数据)
  2. 只显示我的萨尔多
  3. 只显示我的金额

我已经尝试过这段代码

blahlblah.....
  ->where('created_by',Auth::id())
  ->orWhere('amount','LIKE','%'.$search.'%')

->orWhere('saldo','LIKE','%'.$search.'%')

但在此处填写搜索字段时,条件无法正常工作(显示其他用户的数据,例如我的 saldo 和 amount )。

这是输出:

这里是我的完整代码:

MutasiLog::with([
                 'transaction_detail.transaction',
                ])
                ->orWhereHas('transaction_detail', function (&$q) use ($search) {
                  $q->where('id', 'like', '%' . $search . '%');

                $q->orWhereHas('transaction',function($q) use ($search){
                   $q->where('description','LIKE','%'.$search.'%');
                });
      })
      ->where('created_by',Auth::id())
      ->orWhere('amount','LIKE','%'.$search.'%')
      ->orWhere('saldo','LIKE','%'.$search.'%')
      ->offset($start)
      ->limit($limit)
      ->orderBy($order,$dir)
      ->get();

【问题讨论】:

  • 来自文档“您应该始终对 orWhere 调用进行分组,以避免在应用全局范围时出现意外行为。”。你可以找到一个例子there
  • 已解决 - 谢谢 :D ...你能把你的评论回答一下吗?

标签: php laravel eloquent


【解决方案1】:

来自文档“您应该始终对 orWhere 调用进行分组,以避免在应用全局范围时出现意外行为。”。你可以找到一个例子there
所以你可以这样做:

// blahlblah.....

        ->where(function ($query) use ($search) {
            $query->where('created_by',Auth::id())
                  ->orWhere('amount','LIKE','%'.$search.'%')
                  ->orWhere('saldo','LIKE','%'.$search.'%');
        })
        // ...

或者这个,取决于你的需要:

// blahlblah.....
        ->where('created_by',Auth::id())
        ->where(function ($query) use ($search) {
            $query->where('amount','LIKE','%'.$search.'%')
                  ->orWhere('saldo','LIKE','%'.$search.'%');
        })
        // ...

【讨论】:

    【解决方案2】:

    当使用 orWhere 并与其他 where 链接时,您的意思是:获取数据 where created_by me or where amount like search ,这就是为什么要获取所有数据,因此您应该将搜索 orWhere 分组到单个 where 的解决方案,如下所示:

          ->where('created_by',Auth::id())
          ->where(function($query){
             $query->orWhere('amount','LIKE','%'.$search.'%')->orWhere('saldo','LIKE','%'.$search.'%')
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-04
      • 2020-06-27
      • 1970-01-01
      • 1970-01-01
      • 2020-07-09
      相关资源
      最近更新 更多