lundi 26 novembre 2018

Laravel search on multiple models and load relation ship

I made a search class for laravel where I need to search in multiple models but for specific columns with like. At the final I need to return a collection of a Model related to the search term. Ex. I search for a car brand and I need to return all cars that are made by that brand. How could my code speeded up?

public function search($obj, $tags, $path)
{
  $query = $obj::select('*');
  foreach ($tags as $tag) {
     $query->orWhere($tag, 'LIKE', '%' . $this->term . '%');
  }
  $query = $query->get();


  foreach ($path as $pat) {
    if($pat!="")
      $tmp = $query->load([$pat => function ($q) use (&$exams) { $exams = $q->get(); }]);
    else
      $exams = $query;

    if($exams && $exams->count() > 0)
    {
      $this->hits++;

      if(!$this->onlySuggestions) {
        $this->res = $this->res->merge($exams);
      }
      else {
        foreach ($tags as $tag) {
          if($tag!="created_at") {
            $temp = $query;
            $temp = $temp->filter(function ($item) use ($tag){
              return false !== stristr($item->{$tag}, $this->term);
            });

            $this->res = $this->res->merge($temp->pluck($tag));
          }
        }
      }
    }
}

}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire