Laravel 5 - Dedicated Query string filtering on many-to-many Relationship

时间:2016-04-15 11:15:17

标签: php laravel eloquent laravel-5.2

I Followed a tutorial with this source code: https://github.com/laracasts/Dedicated-Query-String-Filtering/tree/master/app

If you have laracasts you can watch the video here

What i like to achieve is filter products based on their category.

When i filter on the product itself , it works fine

class ProductFilter extends QueryFilter

{
    public function categorie($name)
    {
        return $this->builder->where('name' , $name);
    }

}

But when i try to filter on the relationship it doens't work. (i get no errors either) . The error is located in this file , i think

class ProductFilter extends QueryFilter

{
    public function categorie($name)
    {
        return $this->builder->categories()->where('name' , $name);
    }

}

View

<form  method="get" action="/producten/categorie" style="display:inline-block">
 @foreach($roots as $root)
   <li><button type="submit" name="categorie" value="{{$root->name}}" class="button-link">{{$root->name}}</button></li>
 @endforeach
</form>

Route

Route::get('producten/categorie' , 'FrontProductController@index');

FrontProductController

  public function index(ProductFilter $filters)
    {
        Product::filter($filters)->get();

    }

QueryFilter class

abstract class QueryFilter
{
    protected $request;
    protected $builder;

    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    public function apply(Builder $builder)
    {
        $this->builder = $builder;

        foreach ($this->filters() as $name => $value) {
            if (! method_exists($this, $name)) {
                continue;
            }
            if (strlen($value)) {
                $this->$name($value);
            } else {
                $this->$name();
            }
        }
        return $this->builder;

    }

    public function filters()
    {
        return $this->request->all();
    }

}

Product Model

  public function categories()
  {
      return $this->belongsToMany('App\Category')->withTimestamps();
  }

 public function scopeFilter($query, QueryFilter $filters)
   {
       return $filters->apply($query);
   }

1 个答案:

答案 0 :(得分:1)

在产品过滤器中,我需要针对多对多关系执行以下操作:

public function category($name)
    {
        return $this->builder->whereHas('categories', function ($query) use ($name) {
            $query->where('name', $name);
        });
    }