staudenmeir / eloquent-has-many-deep

Laravel Eloquent HasManyThrough relationships with unlimited levels

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Pivots not returned the same way

utherp opened this issue · comments

I'm using hasManyDeepFromRelations, 2 deep, both with morphToMany:
assume all classes use Permissible and extend Model with the below code:

trait Permissible {
    public function permitted_by() { return $this->morphToMany(Role::class, 'target', 'role_target'); }
    public function permitted_through_sets() {
        return $this->hasManyDeepFromRelations($this->in_sets(), (new Set()->permitted_by());
    }
}

abstract class Model extends \Illuminate\Database\Eloquent\Model {
     public function in_sets() { return $this->morphToMany(Set::class, 'target', 'set_target'); }
}

when I call permitted_by through a Set in tinker, I get this:

> $obj->in_sets[0]->permitted_by
= Illuminate\Database\Eloquent\Collection {#5149
    all: [
      App\Models\Role {#4174
        id: 1,
        name: "test1",
        created_at: null,
        updated_at: null,
        filler: null,
        pivot: Illuminate\Database\Eloquent\Relations\MorphPivot {#5148
          target_id: 2,
          role_id: 1,
          target_type: "App\Models\Set",
        },
      },
    ],
  }

but when I call permitted_through_sets, I get this:

> $obj->permitted_through_sets
= Illuminate\Database\Eloquent\Collection {#5126
    all: [
      App\Models\Role {#5130
        id: 1,
        name: "test1",
        created_at: null,
        updated_at: null,
        filler: null,
        laravel_through_key: 12,
      },
    ],
  }

I don't get the pivot object, which is kind of important. I tried adding a call to withPivot, this is what it returned:

> $obj->permitted_through_sets()->withPivot('target_id')
= Illuminate\Database\Eloquent\Collection {#5144
    all: [
      App\Models\Role {#5142
        id: 1,
        name: "test1",
        created_at: null,
        updated_at: null,
        filler: null,
        laravel_through_key: 12,
        target_id: Illuminate\Database\Eloquent\Relations\Pivot {#5151},
      },
    ],
  }

I just get a blank Pivot object on the property of the column name, rather than how it is normally returned, as a pivot object on the pivot property.

I do realize that the pivot may be ambiguous, but it should return at least the last pivot.

...I probably should have put this in discussions first.

Hi @utherp,
No worries.

Pass the name of the table to withPivot():

$obj->permitted_through_sets()->withPivot('TODO', ['target_id'])
                                           ^^^^

I did finally find the solution... I presumed the same signature as laravel's. thanks, this module is awesome! saves me so much extra b.s.