demobiel's avatar

Dynamic Model returned by relationship depending on "type" column

I am trying to figure out how a relationship can return a collection of models, where the model depends on the "type" column.

I have an Entity class

abstract class Entity extends Model{

}

and 2 implementations:

class Video extends Entity{

}
class Book extends Entity{

}

How can I have a polymorphic relation so that I could do $owner->entities() and it would return me a collection of the corresponding models (which can be a mix of Video and Book instances).

0 likes
2 replies
demobiel's avatar

Yes :) but one way or another (and it is not that I am lazy, spending couple of hours on this), I don't see how... I understand the examples given, but I cannot get my head around this one... It seems easy, but I am failing at all attemps.

I am not sure where to put the morph map, should this be on the Owner class or the Entity class? Can in that case Entity still be an abstract class?

I have now this:

class Owner extends Model{
    public entities() : MorphToMany
    {
        //???? here I am stuck...
     }

    protected static boot()
    {
      Relation::morphMap([
           'video' => Video::class,
          'book' => Book::class
      ]);
   }
}

Please or to participate in this conversation.