Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

php - 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?
question from:https://stackoverflow.com/questions/65948826/laravel-eloquent-returning-wrong-data

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...