Laravel 4.1: proper way to retrieve all morphedBy relations?

后端 未结 2 681
感情败类
感情败类 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:45

    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.

    0 讨论(0)
  • 2021-02-09 05:48

    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();
    
    0 讨论(0)
提交回复
热议问题