staudenmeir / eloquent-has-many-deep

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

Usage with laravel-adjacency-list? #149

Closed jp2masa closed 1 year ago

jp2masa commented 2 years ago

Is this library compatible with laravel-adjacency-list?

I'm trying the following code but the relationship returns an empty array:

class Category extends Model
{
    use HasFactory;
    use HasRecursiveRelationships;
    use \Staudenmeir\EloquentHasManyDeep\HasRelationships;

    ...

    public function directSpecifications()
    {
        return $this->belongsToMany(
            Specification::class,
            CategorySpecification::class
        );
    }

    public function specifications()
    {
        return $this->hasManyDeepFromRelations(
            $this->newRelatedInstance(Category::class)->ancestorsAndSelf(),
            $this->newRelatedInstance(Category::class)->directSpecifications()
        );
    }
}
staudenmeir commented 2 years ago

Unfortunately, this kind of combination is not possible because recursive relationships can't be concatenated like "normal" relationships.

What you need instead is a BelongsToManyOfAncestors relationship (equivalent to BelongsToManyOfDescendants) and I'm working on that. I'll give you an update when the relationship is ready.

jp2masa commented 2 years ago

OK, thanks!

JanCusters commented 1 year ago

Any news on the progress @staudenmeir? I came across the same problem :/

staudenmeir commented 1 year ago

I just released new versions for both packages that add support for relationships like yours.

You only need to remove the first ->newRelatedInstance(Category::class):

class Category extends Model
{
    public function specifications()
    {
        return $this->hasManyDeepFromRelations(
            $this->ancestorsAndSelf(),
            $this->newRelatedInstance(Category::class)->directSpecifications()
        );
    }
}