Laravel 4.1: proper way to retrieve all morphedBy relations?

时间秒杀一切 提交于 2019-12-03 08:16:36

Was able to figure it out, would love to hear comments on this implementation.

in Tag.php

public function taggable()
{
    return $this->morphToMany('Tag', 'taggable', 'taggables', 'tag_id')->orWhereRaw('taggables.taggable_type IS NOT NULL');
}

in calling code:

$allItemsHavingThisTag = $tag->taggable()
                ->with('videos')
                ->with('posts')
                ->get();
Federico Stango

I just used this on Laravel 5.2 (not sure if it is a good strategy though):

Tag model:

public function related()
{
    return $this->hasMany(Taggable::class, 'tag_id');
}

Taggable model:

public function model()
{
    return $this->belongsTo( $this->taggable_type, 'taggable_id');
}

To retrieve all the inverse relations (all the entities attached to the requested tag):

@foreach ($tag->related as $related)
    {{ $related->model }}
@endforeach

... sadly this technique doesn't offer eager load functionalities and feels like a hack. At least it makes it simple to check the related model class and show the desired model attributes without much fear to look for the right attributes on the right model.

I posted a similar question in this other thread as I am looking for relations not known in advance.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!