1

I need to get the latest parent in a nested tree with laravel :

Example:

Example

Schema of the table in my database :

enter image description here

Relationships in my model :

public function parentUnit() {
    return $this->belongsTo('Unit', 'unit_id', 'id');
}

public function allParentUnit() {
    return $this->parentUnit()->with('allParentUnit');
}

Question:

How can I get the latest parent in the picture above:

The latest parent of G is A

And the last parent of F is B

1 Answer 1

2

I would add a method to the model to find the first parent.

public function getLatestParent()
{
    if ($this->parentUnit)
        return $this->parentUnit->getLatestParent();

    return $this;
}
Sign up to request clarification or add additional context in comments.

1 Comment

How can I add it in Eloquent Model ??

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.