staudenmeir / eloquent-has-many-deep

Laravel Eloquent HasManyThrough relationships with unlimited levels
MIT License
2.67k stars 157 forks source link

hasManyDeepFromRelations via morph? #141

Closed mattfoster7 closed 3 years ago

mattfoster7 commented 3 years ago

Hi, I have an object which could have one or many distant relations, depending on the intermediate relation.

I want to reliably get a list of a Social Account's seasons and shows. Which would either be via the one Season it belongs to, or the many Seasons its Contestant belongs to.

I have sort of hacked it together below, and it largely works, but anything eager loaded returns null, and it errors if there isn't a relation.

Is there a way to use hasManyDeepFromRelations with a MorphTo relationship?

// Social.php

    public function owner()
    {
        // owner_type = App\Season or App\Contestant
        return $this->morphTo();
    }

   public function seasons()
   {
       // This doesn't work for eager loading
        return optional($this->owner)->seasons();
   }

   public function shows()
   {
       // This works if there IS an owner (not when it's null) but doesn't work for eager loading
       return $this->hasManyDeepFromRelations($this->owner(), (new ($this->owner_type))->shows());
   }
// Contestant.php

    public function seasons()
    {
        return $this->belongsToMany('App\Season')->withPivot(['role'])->withTimestamps();
    }

    public function shows()
    {
        return $this->hasManyDeepFromRelations($this->seasons(), (new \App\Season())->show());
    }
// Season.php

    public function seasons()
    {
        //return array of self
        return $this->hasMany('App\Season', 'id', 'id');
    }

    public function shows()
    {
        //return the single show but wrapped in a collection
        return $this->hasMany('App\Show', 'id', 'show_id');
    }

    public function show()
    {
        return $this->belongsTo('App\Show');
    }
staudenmeir commented 3 years ago

Unfortunately, it's not possible to use hasManyDeepFromRelations() with MorphTo relationships.

mattfoster7 commented 3 years ago

OK!