Say I want to store various bits of data about customers, so I have two models linked by a pivot table, storing the customer's values for each datafield type on the pivot table:
Customer {
public function datafields()
{
return $this->belongsToMany('Datafield')->withPivot('value');
}
}
and
Datafield {
public function customers()
{
return $this->belongsToMany('Customer')->withPivot('value');
}
So my tables are customers, customer_datafield, datafields.
How can I set up a query scope in the customer to find all customers that have a value of x for a specfic datafield?
Something along the lines of
Customer {
public function datafields()
{
return $this->belongsToMany('Datafield')->withPivot('value');
}
public function scopeSearch($query, $searchfor)
{
return $query->datafields()->pivot()
->where('value', $searchfor)
->where('datafield_id', 123);
}
}
I've tried a few methods but not having any luck geting one to work. Any suggestions much appreciated!
Eloquent way for a single fixed pivot field:
This gives you more power and flexibility:
You might be tempted to use
where
with array of values instead offoreach
in the second closure, however it might not work as expected, for fields won't be prefixed with table name.Another solution is to use simple
join
:You can alter it the same way as 2nd example above.
Note: on Laravel 5 you can simply use this: