简体   繁体   中英

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) .

Question

  1. why it ignore where('user_id', '=', $user->id)
  2. How to fix it?

You should group your search LIKE query here

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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