@JorickL - wow that does sound complicated! What I would do is create a table/model that represents all of the things in you application that you can apply a maintenance order, possibly a maintainable with a migration like
$table->primary(id);
$this->morphs('maintainable');
$this->timestamps();
You can then in you maintainable model you can do
public function maintainable() {
return $this->morphsTo();
}
In your polymorphic classes, such as locomotive.
public function maintainable() {
return $this->morphOne(Maintainable::class, 'maintainable');
}
I am not sure if this is right way to use Polymorphic relations but in my usecase (which is similar to yours) it keeps the laravel magic isolated to under the maintainable model/table so the rest of my application just deals with the base table. e.g.
in maintenance orders
public function maintainable() {
return $this->belongsTo(Maintainable::class);
}
in maintainable
public function maintanceOrders() {
return $this->hasmany(MaintenanceOrders);
}
so you can then do something like
Locomotive::first()->maintainable->maintenanceOrders);
MaintenanceOrder::first()->maintainable->maintainable; //should print you the underlying model of the thing the maintenance order applies to.
I found that you have to add a few steps when creating new sub-classes such as locomotive to hook up the maintainable parent but I put these in a Model Observer so it automatically handles this on creating/deletion.
Once you find yourself repeating code in the above scenario for each sub type you can extract a base class that the subtypes inherit from and put shared logic/relationships in there :D
Unfortunately Im not permitted to share my solution as its from my @dayjob and there are IP restrictions otherwise I would (Which is why I have done the above from memory so there might be some mistakes but you should get the general idea).
Hopefully make sense but if not let me know. Also keen too hear if anyone has any thoughts on how I can improve my workflow here as I generally find it a bit icky hence only reaching for it when I have to.