Retrieving all morphedByMany relations in Laravel Eloquent

后端 未结 3 1179
半阙折子戏
半阙折子戏 2020-12-31 01:01

In the Laravel documentation, there is the following example for retrieving morphedByMany relations, which are many-to-many polymorphic relations.

Larav

相关标签:
3条回答
  • 2020-12-31 01:46

    I use a trick here:

    Create a Model Taggable for your connection table taggable and add a hasMany relation to the Tag model.

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

    Within your Taggable model create a morphedTo relation.

    public function taggables()
    {
        return $this->morphTo();
    }
    

    Now you can get all models witch are using the tag by calling:

    $tagged = Tag::with('related.taggables');
    
    0 讨论(0)
  • 2020-12-31 01:51

    You should be able to add a relationship on your Tag class as such

    public function taggable()
    {
        return $this->morphedTo();
    }
    

    That will use the taggable_id and taggable_type to get the relevant Model that it is tied to.

    0 讨论(0)
  • 2020-12-31 01:54

    Did you think to use the "union" function of the collections to merge all the different collection in order to retrieve all what you need?

    class Tag extends Model
    {
        [...]
    
        /**
         * Get all of.
         */
        public function morphed()
        {
            return $this->video->union($this->posts)->all();
        }
    }
    
    0 讨论(0)
提交回复
热议问题