2016-03-18 37 views
1

whereHas Laravel中的方法使用來自MySQL的EXISTS。問題是,當例如品牌和文字指定的時候,所有帶品牌或不帶品牌的文字都存在於文字中......但是,當品牌指定它時,只需要帶有品牌和文字的品牌。 $ parts = AutoPart \ Part :: has('classifier') - > with(['details','classifier','order','place']) - > orderBy('id','desc');有沒有什麼可以嚴格的在Laravel的方法?

if ($brand = $request->get('brand', FALSE)) { 
    $parts->whereHas('details', function($query) use($brand) { 
     $query->where('brand', '=', $brand); 
    }); 
} 

if ($model = $request->get('model', FALSE)) { 
    $parts->whereHas('details', function($query) use($model) { 
     $query->where('model', '=', $model); 
    }); 
} 

if ($text = $request->get('text', FALSE)) { 
    if (strlen($text) > 0) { 
     $parts->whereHas('details', function($query) use($text) { 
      $query->where('notes', 'LIKE', '%' . $text . '%'); 
     }); 

     $parts->orWhereHas('classifier', function($query) use($text) { 
      $query->where('name', 'LIKE', '%' . $text . '%'); 
     }); 
    } 
} 

回答

1

更改的最後一個條件

if ($text = $request->get('text', FALSE)) { 
    if (strlen($text) > 0) { 

     // This will put a bracket around the whereHas and the OrWherehas 
     $parts->where(function($q) use($text) { 
      $q->whereHas('details', function($query) use($text) { 
       $query->where('notes', 'LIKE', '%' . $text . '%'); 
      }); 

      $q->orWhereHas('classifier', function($query) use($text) { 
       $query->where('name', 'LIKE', '%' . $text . '%'); 
      }); 
     }); 

    } 
} 

希望它有助於

相關問題