Eloquent HasMany Abstract Class Relationship

Posted 1 year ago by brysonreece

I'm trying to dynamically handle Eloquent child relationships for a Model I've created.

So far my approach has been the following:

public function sensors() {
    $types = [TemperatureSensor::class, LightSensor::class, AudioSensor::class];
    $sensors = collect();

    foreach($types as $type) {
        $sensors->concat($this->hasMany($type));
    }

    return $sensors;
}

However, I need the ability to return a relationship instance. All of the various Sensor types extend a generic Sensor class. Because of such, I've also tried

public function sensors() {
    return $this->hasMany(Sensor::class);
}

Any ideas?

Please sign in or create an account to participate in this conversation.