Reputation: 2227
So I have a pension type:
class Type extends Base
{
use RecordStatusActiveTrait;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'pn_pension_type';
/**
* The actual primary key for the model.
*
* @var string
*/
protected $primaryKey = 'pension_type_id';
// Belongs To -----
public function pensionClass() {
return $this->belongsTo('App\Models\Control\PensionClass', 'pension_class_id');
}
// Belongs To Many -----
public function qualifiers()
{
return $this->belongsToMany('App\Models\Pension\Qualifier', 'pn_pension_type_qualifier', 'type_id', 'qualifier_id');
}
}
And a pension Qualifier:
class Qualifier extends Base
{
use RecordStatusActiveTrait;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'pn_pension_qualifier';
/**
* The attributes that should be casted to native types.
*
* @var array
*/
protected $casts = [
'rules' => 'array',
];
// Belongs To Many -----
public function types()
{
return $this->belongsToMany('App\Models\Pension\Type', 'pn_pension_type_qualifier', 'qualifier_id', 'type_id');
}
}
They have a many to many relationship with a table in between as normal. I would like to grab a set of pension types and find the unique Qualifiers between all of them. I COULD just foreach through each of their qualifiers and end up with a list of unique qualifiers but I was wondering if their was an "Eloquent" way.
Upvotes: 1
Views: 951
Reputation: 687
Using whereHas
will allow you to restrict the results based on the relation. In regards to what you want, you'd want to query from your Qualifiers like so.
Qualifiers::whereHas('pensions', function($query) use ($pensionIds) {
$query->whereIn('id', $pensionIds);
})->distinct()->get();
Adding on ->distinct()
will then get you the unique entries.
Upvotes: 1