samedi 15 décembre 2018

Laravel Eloquent - not retrieving required rows

Making use of search box on the app, database have 2 tables like below:

 ________________
|**Services**
 ________________
|=>id
|=>name
|=>description
|=>other_columns
________________

and:

 ________________
|**Products**
 ________________
|=>id
|=>name
|=>description
|=>service_id
|=>other_columns
________________

=>each Service contains many Products

=>Due to the form of the search box:

enter image description here

user can search for a word for products and optionally choose a service, thus, the eloquent that I use to retrieve results for:

  1. if user didn't choose a specific service to search in:

    $data = Product::where('name','like',"%$search_value%")
            ->orWhere('description','like',"%$search_value%")
            ->orWhere('description_long','like',"%$search_value%")
            ->paginate($items_per_page);
    
    
  2. if user did choose a specific service:

    $data = Product::where([
                ['name','like',"%$search_value%"],
                ['service_id','=',"%$service%"],
            ])
            ->orWhere([
                ['description','like',"%$search_value%"],
                ['service_id','=',"%$service%"],
            ])
            ->orWhere([
                ['description_long','like',"%$search_value%"],
                ['service_id','=',"%$service%"],
            ])
            ->paginate($items_per_page);
    
    

Models relations are like below:

  1. Product Model:

    public function service(){
        return $this->belongsTo(Service::class);
    }
    
    
  2. Service Model:

    public function products(){
        return $this->hasMany(Product::class);
    }
    
    

In both cases $data always contain all rows of products. how to achieve the right result?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire