-
follow https://laravel.com/docs/master/eloquent-relationships#many-to-many-polymorphic-relations except
Defining The Inverse Of The Relationship
, instead we will use the below -
thanx to setup oneToMany relation between
tag & taggable
under taggable model
<?php
use Illuminate\Database\Eloquent\Relations\MorphPivot;
class Taggable extends MorphPivot
{
protected $table = 'taggables';
/* -------------------------------------------------------------------------- */
/* RELATIONS */
/* -------------------------------------------------------------------------- */
public function tag()
{
return $this->belongsTo(Tag::class);
}
public function related()
{
return $this->morphTo(__FUNCTION__, 'taggable_type', 'taggable_id');
}
}
under tag model
<?php
class Tag extends Model
{
protected $with = ['taggables.related'];
/* -------------------------------------------------------------------------- */
/* RELATIONS */
/* -------------------------------------------------------------------------- */
public function taggables()
{
return $this->hasMany(Taggable::class);
}
/* -------------------------------------------------------------------------- */
/* ACCESSORS */
/* -------------------------------------------------------------------------- */
public function getRelatedModelsAttribute()
{
return $this->taggables->groupBy('taggable_type');
}
}
under the related model
<?php
public function tags()
{
return $this->morphToMany(Tag::class, 'taggable')
->using(Taggable::class);
}
now use it like
Tag::first()->related_models;
update
related
method according to docs as with plain$this->morphTo()
we would getnull
instead