代码之家  ›  专栏  ›  技术社区  ›  mafortis

Laravel雄辩地返回了错误的数据

  •  0
  • mafortis  · 技术社区  · 4 年前

    我有条件数据,它在返回数据时忽略了这些条件:

    工作良好

    $orders = Order::where('user_id', $user->id)->with(['customer', 'laundry', 'driver', 'driver.user', 'progresses' => function($p){
      $p->orderby('created_at', 'asc');
    }, 'progresses.progress', 'services'])->get();
    

    返回错误数据

    $orders = Order::where('user_id', $user->id)->with(['customer', 'laundry', 'driver', 'driver.user', 'progresses' => function($p){
                    $p->orderby('created_at', 'asc');
                }, 'progresses.progress', 'services'])
                ->where('id', 'like', '%'.$this->search.'%')
                ->orWhere('transport', 'like', '%'.$this->search.'%')
                ->orWhere('amount', 'like', '%'.$this->search.'%')
                ->orWhere('weight', 'like', '%'.$this->search.'%')
                ->orWhere('total', 'like', '%'.$this->search.'%')
                ->paginate(10);
    

    问题

    第二个查询返回全部 orders 并忽略 where('user_id', '=', $user->id) .

    提问

    1. 为什么它忽略 其中('user_id','=',$user->id)
    2. 如何修复它?
    0 回复  |  直到 4 年前
        1
  •  2
  •   Jerson    4 年前

    您应该对搜索进行分组 LIKE 在此处查询

    Order::with(
         [
           'customer', 
           'laundry', 
           'driver', 
           'driver.user', 
           'progresses' => function($p) {
              $p->orderby('created_at', 'asc');
           }, 
           'progresses.progress', 
           'services'
         ]
        )->where('user_id', $user->id)
        ->where(function($q) {
            $q->where('id', 'like', '%'.$this->search.'%')
            ->orWhere('transport', 'like', '%'.$this->search.'%')
            ->orWhere('amount', 'like', '%'.$this->search.'%')
            ->orWhere('weight', 'like', '%'.$this->search.'%')
            ->orWhere('total', 'like', '%'.$this->search.'%');
        })->paginate(10);
    

    所以查询字符串看起来像:

    WHERE user_id = ? 
    AND 
    (id LIKE ? OR transport LIKE ? OR amount LIKE ? OR weight LIKE ? OR total LIKE ?)
    

    它将忽略 where('user_id', '=', $user->id) 因为 orWhere 在您的搜索 喜欢 查询