Laravel 4.1: proper way to retrieve all morphedBy relations?

后端 未结 2 849
野的像风
野的像风 2021-02-09 05:40

Just migrated to 4.1 to take advantage of this powerful feature. everything seems to work correctly when retrieving individual \'morphedByXxxx\' relations, however when trying t

2条回答
  •  我寻月下人不归
    2021-02-09 05:44

    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.

提交回复
热议问题