So, digging around, I found out how this could be implemented.
Before
public function scopeInDeviceGroup($query, $deviceGroup)
{
return $query->whereIn($query->qualifyColumn('device_id'), function ($query) use ($deviceGroup) {
$query->select('device_id')
->from('device_group_device')
->where('device_group_id', $deviceGroup);
});
}
After:
public function scopeInDeviceGroup($query, $deviceGroup)
{
// Build the comma-separated list of device IDs in SQL
$deviceIdsSubquery = \DB::table('device_group_device')
->where('device_group_id', $deviceGroup)
->pluck('device_id')
->implode(',');
// Use the result in the whereIn clause
return $query->whereIn($query->qualifyColumn('device_id'), explode(',', $deviceIdsSubquery));
}
The performance, while still not instant, is way better than before.