Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[11.x] Add Recursive Hierarchy Root ID Retrieval Method for Model getHierarchyRootId #54556

Conversation

pandiselvamm
Copy link

@pandiselvamm pandiselvamm commented Feb 11, 2025

Add method getHierarchyRootId(string $parentFieldName = 'parent_id') to get the root ID of the hierarchy for the given model.

Category Table

ID Name Parent ID
1 Electronics NULL
2 Laptops 1
3 Gaming Laptops 2
4 Ultrabooks 2
5 Smartphones 1
6 Accessories NULL
7 Headphones 6

Scenario: Finding the root parent of id = 3 (Gaming Laptops)

1️⃣ Gaming Laptops (id=3) → Parent ID = 2 (Laptops)
2️⃣ Laptops (id=2) → Parent ID = 1 (Electronics)
3️⃣ Electronics (id=1) → Parent ID = NULL (Root Parent Found)

Final Output: 1 (Electronics)

Usage:


class Category extends Model
{
    use HasFactory, HasHierarchy;

    protected $fillable = ['name', 'parent_id'];
}

$rootId = Category::find(3)->getHierarchyRootId();
echo "Root Parent ID: " . $rootId;

@pandiselvamm pandiselvamm changed the title [11.x] Add method to get the root parent ID of the hierarchy for the given model. [11.x] Add Recursive Hierarchy Parent ID Retrieval Method for Model getHierarchyParentId Feb 11, 2025
@pandiselvamm pandiselvamm marked this pull request as draft February 11, 2025 10:39
@shaedrich
Copy link
Contributor

Wouldn't getHierarchyRootId() be more intuitive?

@pandiselvamm pandiselvamm changed the title [11.x] Add Recursive Hierarchy Parent ID Retrieval Method for Model getHierarchyParentId [11.x] Add Recursive Hierarchy Root ID Retrieval Method for Model getHierarchyRootId Feb 11, 2025
@pandiselvamm pandiselvamm force-pushed the feat/model-get-parent-heirarchy-id branch from 185074a to 106937c Compare February 11, 2025 13:21
@pandiselvamm pandiselvamm deleted the feat/model-get-parent-heirarchy-id branch February 11, 2025 13:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants