简体   繁体   English

Laravel eloquent 返回错误数据

[英]Laravel eloquent returning wrong data

I have conditional data and it ignores that conditions while returning data:我有条件数据,它在返回数据时忽略了这些条件:

Works fine工作正常

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

Return wrong data返回错误数据

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

Issue问题

The second query return all orders and ignores where('user_id', '=', $user->id) .第二个查询返回所有orders并忽略where('user_id', '=', $user->id)

Question问题

  1. why it ignore where('user_id', '=', $user->id)为什么它忽略where('user_id', '=', $user->id)
  2. How to fix it?如何解决?

You should group your search LIKE query here您应该在这里对您的搜索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);

So the query string is look like:所以查询字符串看起来像:

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

It will ignore the where('user_id', '=', $user->id) because of orWhere on your search LIKE query它将忽略where('user_id', '=', $user->id)因为orWhere在您的搜索LIKE查询

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM