staudenmeir / laravel-adjacency-list

Recursive Laravel Eloquent relationships with CTEs
MIT License
1.33k stars 109 forks source link

hasManyOfAncestorsAndSelf #242

Closed MiladAheshmeh closed 3 months ago

MiladAheshmeh commented 3 months ago

Is there a method similar to hasManyOfDescendantsAndSelf to get the ancestorsAndSelf recursive posts?

staudenmeir commented 3 months ago

Hi @MiladAheshmeh, You can achieve this with concatenation: https://github.com/staudenmeir/laravel-adjacency-list?tab=readme-ov-file#deep-relationship-concatenation

class User extends Model
{
    use \Staudenmeir\EloquentHasManyDeep\HasRelationships;
    use \Staudenmeir\LaravelAdjacencyList\Eloquent\HasRecursiveRelationships;

    public function recursivePosts()
    {
        return $this->hasManyDeepFromRelations(
            $this->ancestorsAndSelf(),
            (new static)->posts()
        );
    }

    public function posts()
    {
        return $this->hasMany(Post::class);
    }
}

$recursivePosts = User::find($id)->recursivePosts;
MiladAheshmeh commented 3 months ago

class Archive extends Model {   

    use \Staudenmeir\EloquentHasManyDeep\HasRelationships;
    use \Staudenmeir\LaravelAdjacencyList\Eloquent\HasRecursiveRelationships;

    public function user(): BelongsTo {
        return $this->belongsTo(User::class);
    }

    public function ancestorsAndSelfUsers() {
        ?????
    }   

}

how to create ancestorsAndSelfUsers method

Archive -> belongsTo -> User

Archive is a recursive model

staudenmeir commented 3 months ago

Same procedure:

class Archive extends Model {   

    use \Staudenmeir\EloquentHasManyDeep\HasRelationships;
    use \Staudenmeir\LaravelAdjacencyList\Eloquent\HasRecursiveRelationships;

    public function user(): BelongsTo {
        return $this->belongsTo(User::class);
    }

    public function ancestorsAndSelfUsers() {
            return $this->hasManyDeepFromRelations(
                $this->ancestorsAndSelf(),
                (new static)->user()
            );
    }   

}
MiladAheshmeh commented 3 months ago

it's work Thanks