我在Laravel和很多人之间遇到了一些麻烦。
我有以下结构: 传感器 - >传感器组 - >用途
所以传感器可以属于多个组,一个组可以有多个“用法”。
传感器类如下所示:
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');
}
}
sensorgroup类如下所示:
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');
}
}
,用法类看起来像这样:
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');
}
}
现在我想获取传感器的所有组,但前提是该传感器组附加到某些特定的“用法”。
要获取一个传感器的所有传感器组,我可以使用:
$sensor = App\sensor::find($sensorId);
$groups = $sensor->groups();
但我无法弄清楚如何添加条件以仅获取附加到特定用途的传感器组。有什么想法吗?
答案 0 :(得分:1)
使用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();