eloquent-has-many-deep icon indicating copy to clipboard operation
eloquent-has-many-deep copied to clipboard

Usage with laravel-adjacency-list?

Open jp2masa opened this issue 3 years ago • 2 comments

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()
        );
    }
}

jp2masa avatar Jan 07 '22 20:01 jp2masa

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.

staudenmeir avatar Jan 07 '22 21:01 staudenmeir

OK, thanks!

jp2masa avatar Jan 07 '22 23:01 jp2masa

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

JanCusters avatar Nov 16 '22 13:11 JanCusters

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()
        );
    }
}

staudenmeir avatar Nov 17 '22 07:11 staudenmeir