How to define relationships when using interfaces

The normal use of polymorphic relationships in Laravel is pretty well covered by the Post-User-Image example.

I am trying to find a clean way to implement relationships, to say that the relationship is Article / ContentA / ContentB.

articles id content_1 id content_2 id user_defined_content_n id contentables article_id contentable_id contentable_type // content_2, user_defined_content_n 

Content classes are not necessarily known in the article, so defining an article model with many MorphedByMany relationships MorphedByMany not the way I want to do this.

Perhaps I am badly structuring my classes. I could create a ContentEntity class that translates to separate Content classes, but I would like to avoid this if possible.


Perhaps this better explains my problem.

 class Article extends Model { public function contentEntities() { return $this->hasMany(ContentEntity::class); } } class ContentEntity extends Model { public function contentable() { return $this->morphTo(); } } class Content extends Model { public function contentEntity() { return $this->morphOne(ContentEntity::class, 'contentable'); } } class Video extends Model { public function contentEntity() { $this->morphOne(ContentEntity::class, 'contentable'); } } 

It works, but it seems very unclean to me. I think it adds too much overhead for developers to manage the ContentEntity parent.

Edit: If someone does not provide a better solution, I went with an EAV style solution using ContentEntity s.

+7
inheritance php laravel laravel-5
source share
1 answer

You can always extract the relationship to a feature to simplify maintenance and expansion in the future:

Tre

 trait Contentable { public function contentEntity() { if(property_exists($this, 'contentable') && $contentable == 'many') { return $this->hasMany(ContentEntity::class); } else { return $this->morphOne(ContentEntity::class, 'contentable'); } } // Future implementations } 

Then all you have to do is use the trait in different objects:

Models

 class Content extends Model { use Contentable; } class Video extends Model { use Contentable; } class Article extends Model { use Contentable; protected $contentable = 'many'; } 
0
source share

All Articles