- follow https://laravel.com/docs/master/eloquent-relationships#many-to-many-polymorphic-relations as usual
- thanx to setup oneToMany relation between
tag & taggable
under taggable model add
<?php
class Taggable extends Model
{
protected $with = ['related'];
public $timestamps = false;
/* -------------------------------------------------------------------------- */
/* RELATIONS */
/* -------------------------------------------------------------------------- */
public function tag()
{
return $this->belongsTo(Tag::class);
}
public function related()
{
return $this->morphTo();
}
}under tag model add
<?php
class Tag extends Model
{
protected $with = ['taggables'];
public $timestamps = false;
/* -------------------------------------------------------------------------- */
/* RELATIONS */
/* -------------------------------------------------------------------------- */
public function taggables()
{
return $this->hasMany(Taggable::class);
}
/* -------------------------------------------------------------------------- */
/* ACCESSORS */
/* -------------------------------------------------------------------------- */
public function getItemsAttribute()
{
return $this->taggables
->groupBy('taggable_type')
->map(function ($v, $k) {
return app($k)->whereIn('id', $v->pluck('taggable_id'))->get();
})->all();
}
}and now use it like
Tag::first()->items;
update
relatedmethod according to docs as with plain$this->morphTo()we would getnullinstead