-
Notifications
You must be signed in to change notification settings - Fork 122
Filtering By Relationships
There are two ways to filter by related models. Using the
$relations
array to define the input to be injected into the related Model's filter. If the related model doesn't have a model filter of it's own or you just want to define how to filter that relationship locally instead of adding the logic to that Model's filter then use therelated()
method to filter by a related model that doesn't have a ModelFilter. You can even combine the 2 and define which input fields in the$relations
array you want to use that Model's filter for as well as use therelated()
method to define local methods on that same relation. Both methods nest the filter constraints into the samewhereHas()
query on that relation.
For both examples we will use the following models:
A App\User
that hasMany
App\Client::class
:
class User extends Model
{
use Filterable;
public function clients()
{
return $this->hasMany(Client::class);
}
}
And each App\Client
belongs to App\Industry::class
:
class Client extends Model
{
use Filterable;
public function industry()
{
return $this->belongsTo(Industry::class);
}
public function scopeHasRevenue($query)
{
return $query->where('total_revenue', '>', 0);
}
}
We want to query our users and filter them by the industry and volume potential of their clients that have done revenue in the past.
Input used to filter:
$input = [
'industry' => '5',
'potential_volume' => '10000'
];
Both methods will invoke a setup query on the relationship that will be called EVERY time this relationship is queried. The setup methods signature is {$related}Setup()
and is injected with an instance of that relations query builder. For this example let's say when querying users by their clients I only ever want to show agents that have clients with revenue. Without choosing wich method to put it in (because sometimes we may not have all the input and miss the scope all together if we choose the wrong one) and to avoid query duplication by placing that constraint on ALL methods for that relation we call the related setup method in the UserFilter
like:
class UserFilter extends ModelFilter
{
public function clientsSetup($query)
{
return $query->hasRevenue();
}
}
This prepend all queries with the hasRevenue()
whenever the UserFilter
runs any constriants on the clients()
relationship. If there are no queries to the clients()
relationship then this method will not be invoked.
You can learn more about scopes here
The related()
method is a little easier to setup and is great if you aren't going to be using the related Model's filter to ever filter that Model explicitly. The related()
method takes the same parameters as the Eloquent\Builder
's where()
method except for the first parameter being the relationship name.
UserFilter
with an industry()
method that uses the ModelFilter
's related()
method
class UserFilter extends ModelFilter
{
public function industry($id)
{
return $this->related('clients', 'industry_id', '=', $id);
// This would also be shorthand for the same query
// return $this->related('clients', 'industry_id', $id);
}
public function potentialVolume($volume)
{
return $this->related('clients', 'potential_volume', '>=', $volume);
}
}
Or you can even pass a closure as the second argument which will inject an instance of the related model's query builder like:
$this->related('clients', function($query) use ($id)
{
return $query->where('industry_id', $id);
});
Add the relation in the $relations
array with the name of the relation as referred to on the model as the key and an array of input keys that was passed to the filter()
method.
The related model MUST have a ModelFilter associated with it. We instantiate the related model's filter and use the input values from the $relations
array to call the associated methods.
This is helpful when querying multiple columns on a relation's table while avoiding multipe whereHas()
calls for the same relationship. For a single column using a $this->whereHas()
method in the model filter works just fine. In fact, under ther hood the model filter applies all constraints in the whereHas()
method.
UserFilter
with the relation defined so it's able to be queried.
class UserFilter extends ModelFilter
{
public $relations = [
'clients' => ['industry', 'potential_volume'],
];
}
ClientFilter
with the industry
method that's used to filter:
Note: The
$relations
array should identify the relation and the input key to filter by that relation. Just as theModelFilter
works, this will access the camelCased method on that relation's filter. If the above example was using the keyindustry_type
for the input the relations array would be$relations = ['clients' => ['industry_type']]
and theClientFilter
would have the methodindustryType()
.
class ClientFilter extends ModelFilter
{
public $relations = [];
public function industry($id)
{
return $this->where('industry_id', $id);
}
public function potentialVolume($volume)
{
return $this->where('potential_volume', '>=', $volume);
}
}
You can even use both together and it will produce the same result and only query the related model once. An example would be:
If the following array is passed to the filter()
method:
[
'name' => 'er',
'last_name' => ''
'company_id' => 2,
'roles' => [1,4,7],
'industry' => 5,
'potential_volume' => '10000'
]
In app/ModelFilters/UserFilter.php
:
<?php namespace App\ModelFilters;
use EloquentFilter\ModelFilter;
class UserFilter extends ModelFilter
{
public $relations = [
'clients' => ['industry'],
];
public function clientsSetup($query)
{
return $query->hasRevenue();
}
public function name($name)
{
return $this->where(function($q)
{
return $q->where('first_name', 'LIKE', $name . '%')->orWhere('last_name', 'LIKE', '%' . $name.'%');
});
}
public function potentialVolume($volume)
{
return $this->related('clients', 'potential_volume', '>=', $volume);
}
public function lastName($lastName)
{
return $this->where('last_name', 'LIKE', '%' . $lastName);
}
public function company($id)
{
return $this->where('company_id',$id);
}
public function roles($ids)
{
return $this->whereHas('roles', function($query) use ($ids)
{
return $query->whereIn('id', $ids);
});
}
}
Sometimes, based on the value of a parameter you may need to push data to a relation filter. The push()
method does just this.
It accepts one argument as an array of key value pairs or to arguments as a key value pair push($key, $value)
.
Related models are filtered AFTER all local values have been executed you can use this method in any filter method.
This avoids having to query a related table more than once. For Example:
public $relations = [
'clients' => ['industry', 'status'],
];
public function statusType($type)
{
if($type === 'all') {
$this->push('status', 'all');
}
}
The above example will pass 'all'
to the stats()
method on the clients
relation of the model.
Calling the
push()
method in thesetup()
method will allow you to push values to the input for filter it's called on