ErikL ErikL - 5 months ago 20
PHP Question

Laravel, querying through many-to-many relationships

I have some trouble with Laravel and many to many relationships.

I have the following structure:
Sensor -> sensor group -> usages

so a sensor can belong to many groups, and a group can have multiple "usages".

The sensor class looks like this:

class sensor extends Model {

protected $table = 'sensor';
protected $primaryKey = 's_id';

public function groups()
{
return $this->belongsToMany('App\sensorgroup','sensor_sensorgroup','ssg_s_id','ssg_sg_id');
}
}


the sensorgroup class looks like this:

class sensorgroup extends Model {

protected $table = 'sensorgroup';
protected $primaryKey = 'sg_id';

public function sensors()
{
return $this->belongsToMany('App\sensor', 'sensor_sensorgroup','ssg_sg_id','ssg_s_id');
}

public function usages()
{
return $this->belongsToMany('App\sensorgroupUsage','sensorGroup_sensorGroupUsage','sgsgu_sg_id','sgsgu_sgu_id');
}
}


and the usages class looks like this:

class sensorgroupUsage extends Model {

protected $table = 'SensorGroupUsage';
protected $primaryKey = 'sgu_id';
protected $fillable = ['sg_name'];

public function sensorgroups()
{
return $this->belongsToMany('App\sensorgroup','sensorGroup_sensorGroupUsage','sgsgu_sgu_id','sgsgu_sg_id');
}

}


Now I want to get all groups for a sensor, but only if that sensor group is attached to some specific "usage".

To get all sensorgroups for one sensor, I can use this:

$sensor = App\sensor::find($sensorId);
$groups = $sensor->groups();


I can't however figure out how to add the condition to only get the sensor groups that are attached to a specific usage. Any ideas?

Answer

Use whereHas method

$usergesId = //here must be an array with useges id
$sensor = App\sensor::find($sensorId);
$groups = $sensor->groups()->whereHas('usages', function ($query) use($usergesId) {
    $query->whereIn('sgu_id', $usagesId);
})->get();