### Install Laravel Adjacency List Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Installs the Laravel Adjacency List package using Composer. This command is compatible with standard command prompts and PowerShell. ```bash composer require staudenmeir/laravel-adjacency-list:"^1.0" ``` ```powershell composer require staudenmeir/laravel-adjacency-list:"^^^^1.0" ``` -------------------------------- ### Nested Tree Structure Example Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Provides an example of the JSON output after applying the toTree() method, illustrating the nested structure with 'children' arrays. ```json [ { "id": 1, "children": [ { "id": 2, "children": [ { "id": 3, "children": [] } ] }, { "id": 4, "children": [ { "id": 5, "children": [] } ] } ] } ] ``` -------------------------------- ### Including Cycle Start Information Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Shows how to include information about the start of a cycle by overriding both enableCycleDetection() and includeCycleStart() to return true. This adds an 'is_cycle' column to the results. ```php class User extends Model { public function enableCycleDetection(): bool { return true; } public function includeCycleStart(): bool { return true; } } $users = User::find($id)->descendants; foreach ($users as $user) { dump($user->is_cycle); } ``` -------------------------------- ### Nested Tree Structure Example Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Provides an example JSON output representing a nested tree structure generated by the toTree() method, illustrating the recursive 'children' relationships. ```json [ { "id": 1, "children": [ { "id": 2, "children": [ { "id": 3, "children": [] } ] }, { "id": 4, "children": [ { "id": 5, "children": [] } ] } ] } ] ``` -------------------------------- ### Include Cycle Start Information Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Shows how to include information about the start of a cycle, marking nodes that are part of a cycle with an `is_cycle` column. This helps in identifying and analyzing cycles within the graph. ```php class Node extends Model { public function enableCycleDetection(): bool { return true; } public function includeCycleStart(): bool { return true; } } $nodes = Node::find($id)->descendants; foreach ($nodes as $node) { dump($node->is_cycle); } ``` -------------------------------- ### Graph Relationship Usage Examples Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Provides examples of how to use the relationships provided by the HasGraphRelationships trait, such as fetching ancestors, descendants, children, and performing operations like counting or updating. ```php $ancestors = Node::find($id)->ancestors; $nodes = Node::with('descendants')->get(); $nodes = Node::has('children')->get(); $total = Node::find($id)->descendants()->count(); Node::find($id)->descendants()->update(['active' => false]); Node::find($id)->parents()->delete(); ``` -------------------------------- ### Example Nested Tree Output (JSON) Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Provides a sample JSON structure illustrating the output generated by the `toTree()` method, showing how nodes are nested using the 'children' key. ```json [ { "id": 1, "children": [ { "id": 2, "children": [ { "id": 3, "children": [] } ] }, { "id": 4, "children": [ { "id": 5, "children": [] } ] } ] } ] ``` -------------------------------- ### Relationship Checking Methods Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Provides an overview and usage examples for methods that check relationships between models: isChildOf, isParentOf, and getDepthRelatedTo. ```php $rootUser = User::create(['parent_id' => null]); $firstLevelUser = User::create(['parent_id' => $rootUser->id]); $secondLevelUser = User::create(['parent_id' => $firstLevelUser->id]); $isChildOf = $secondLevelUser->isChildOf($firstLevelUser); // Output: true $isParentOf = $rootUser->isParentOf($firstLevelUser); // Output: true $depthRelatedTo = $secondLevelUser->getDepthRelatedTo($rootUser); // Output: 2 ``` -------------------------------- ### Deep Relationship Concatenation Example Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Demonstrates how to concatenate recursive relationships using the eloquent-has-many-deep package. This allows fetching posts of a user's descendants by defining a deep relationship. ```php class User extends Model { use \Staudenmeir\EloquentHasManyDeep\HasRelationships; use \Staudenmeir\LaravelAdjacencyList\Eloquent\HasRecursiveRelationships; public function descendantPosts(): \Staudenmeir\EloquentHasManyDeep\HasManyDeep { return $this->hasManyDeepFromRelations( $this->descendants(), (new static)->posts() ); } public function posts() { return $this->hasMany(Post::class); } } $descendantPosts = User::find($id)->descendantPosts; ``` -------------------------------- ### Tree Query Scope Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Explains how to use the `tree()` query scope to retrieve all models starting from the root(s). It also covers `treeOf()` for custom root constraints and specifying a maximum depth for the tree traversal. ```php $tree = User::tree()->get(); $constraint = function ($query) { $query->whereNull('parent_id')->where('list_id', 1); }; $tree = User::treeOf($constraint)->get(); $tree = User::tree(3)->get(); $tree = User::treeOf($constraint, 3)->get(); ``` -------------------------------- ### Define Deep Relationships with Descendants Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Illustrates how to define deep relationships by concatenating recursive relationships with other Eloquent relationships using the eloquent-has-many-deep package. This example fetches all posts of a node's descendants. ```php class Node extends Model { use \Staudenmeir\EloquentHasManyDeep\HasRelationships; use \Staudenmeir\LaravelAdjacencyList\Eloquent\HasGraphRelationships; public function descendantPosts(): \Staudenmeir\EloquentHasManyDeep\HasManyDeep { return $this->hasManyDeepFromRelations( $this->descendants(), (new static)->posts() ); } public function posts() { return $this->hasMany(Post::class); } } $descendantPosts = Node::find($id)->descendantPosts; ``` -------------------------------- ### Included Relationships Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Demonstrates the usage of various predefined relationships provided by the adjacency list trait for querying hierarchical data. These include ancestors, descendants, children, parents, and siblings, with examples showing how to access them and perform related operations like counting or updating. ```php $ancestors = User::find($id)->ancestors; $users = User::with('descendants')->get(); $users = User::whereHas('siblings', function ($query) { $query->where('name', 'John'); })->get(); $total = User::find($id)->descendants()->count(); User::find($id)->descendants()->update(['active' => false]); User::find($id)->siblings()->delete(); ``` -------------------------------- ### MorphToManyOfDescendants Relationship Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Defines a MorphToMany relationship to retrieve all tags of a user and their descendants. Includes an example for retrieving only descendants' tags. ```php class User extends Model { public function tags() { return $this->morphToMany(Tag::class, 'taggable'); } } class User extends Model { public function recursiveTags() { return $this->morphToManyOfDescendantsAndSelf(Tag::class, 'taggable'); } } $recursiveTags = User::find($id)->recursiveTags; $users = User::withCount('recursiveTags')->get(); class User extends Model { public function descendantTags() { return $this->morphToManyOfDescendants(Tag::class, 'taggable'); } } ``` -------------------------------- ### HasManyOfDescendants Relationship Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Defines a HasMany relationship to retrieve all posts of a user and their descendants. Includes an example for retrieving only descendants' posts. ```php class User extends Model { public function posts() { return $this->hasMany(Post::class); } } class User extends Model { public function recursivePosts() { return $this->hasManyOfDescendantsAndSelf(Post::class); } } $recursivePosts = User::find($id)->recursivePosts; $users = User::withCount('recursivePosts')->get(); class User extends Model { public function descendantPosts() { return $this->hasManyOfDescendants(Post::class); } } ``` -------------------------------- ### Get Subgraph with Custom Constraint Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Demonstrates how to use the `subgraph()` query scope to retrieve a specific portion of the graph based on a custom constraint. This allows for targeted data retrieval. ```php $constraint = function ($query) { $query->whereIn('id', $ids); }; $subgraph = Node::subgraph($constraint)->get(); ``` -------------------------------- ### MorphedByManyOfDescendants Relationship Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Defines a MorphedByMany relationship to retrieve all posts of a category and their descendants. Includes an example for retrieving only descendants' posts. ```php class Category extends Model { public function posts() { return $this->morphedByMany(Post::class, 'categorizable'); } } class Category extends Model { public function recursivePosts() { return $this->morphedByManyOfDescendantsAndSelf(Post::class, 'categorizable'); } } $recursivePosts = Category::find($id)->recursivePosts; $categories = Category::withCount('recursivePosts')->get(); class Category extends Model { public function descendantPosts() { return $this->morphedByManyOfDescendants(Post::class, 'categorizable'); } } ``` -------------------------------- ### BelongsToManyOfDescendants Relationship Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Defines a BelongsToMany relationship to retrieve all roles of a user and their descendants. Includes an example for retrieving only descendants' roles. ```php class User extends Model { public function roles() { return $this->belongsToMany(Role::class); } } class User extends Model { public function recursiveRoles() { return $this->belongsToManyOfDescendantsAndSelf(Role::class); } } $recursiveRoles = User::find($id)->recursiveRoles; $users = User::withCount('recursiveRoles')->get(); class User extends Model { public function descendantRoles() { return $this->belongsToManyOfDescendants(Role::class); } } ``` -------------------------------- ### Apply Custom Constraints to Recursive Queries Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Demonstrates how to add custom constraints to the Common Table Expression (CTE) used in recursive queries. This example shows filtering out inactive nodes and their descendants. ```php $descendants = Node::withQueryConstraint(function (Builder $query) { $query->where('nodes.active', true); }, function () { return Node::find($id)->descendants; }); ``` -------------------------------- ### Get Subgraph with Max Depth Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Illustrates how to retrieve a subgraph up to a specified maximum depth. This is useful for limiting the scope of the graph traversal. ```php $constraint = function ($query) { $query->whereIn('id', $ids); }; $subgraph = Node::subgraph($constraint, 3)->get(); ``` -------------------------------- ### Accessing Relative Node Depth in Laravel Adjacency List (PHP) Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Shows how to access the `depth` column included in ancestor, descendant, and subgraph query results, which indicates the node's depth relative to the query's starting node. ```PHP $descendantsAndSelf = Node::find($id)->descendantsAndSelf()->depthFirst()->get(); echo $descendantsAndSelf[0]->depth; // 0 echo $descendantsAndSelf[1]->depth; // 1 echo $descendantsAndSelf[2]->depth; // 2 ``` -------------------------------- ### Concatenating Recursive and Deep Relationships in Laravel Adjacency List (PHP) Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Shows how to combine recursive relationships like `descendants()` with other relationships using `staudenmeir/eloquent-has-many-deep` to create deep relationships, such as getting all posts belonging to a node's descendants. Requires the `HasRelationships` trait. ```php class Node extends Model { use \Staudenmeir\EloquentHasManyDeep\HasRelationships; use \Staudenmeir\LaravelAdjacencyList\Eloquent\HasGraphRelationships; public function descendantPosts(): \Staudenmeir\EloquentHasManyDeep\HasManyDeep { return $this->hasManyDeepFromRelations( $this->descendants(), (new static)->posts() ); } public function posts() { return $this->hasMany(Post::class); } } $descendantPosts = Node::find($id)->descendantPosts; ``` -------------------------------- ### Override Depth Column Name Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Provides an example of how to override the default `depth` column name by implementing the `getDepthName()` method in the model. This is useful if the table already has a `depth` column. ```php class Node extends Model { public function getDepthName(): string { return 'depth'; } } ``` -------------------------------- ### Ordering Models Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Explains the query scopes for ordering models in a breadth-first or depth-first manner, using `breadthFirst()` and `depthFirst()` respectively. ```php $tree = User::tree()->breadthFirst()->get(); $descendants = User::find($id)->descendants()->depthFirst()->get(); ``` -------------------------------- ### Loading Tree Relationships Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Demonstrates how to chaperone tree relationships to load ancestor and parent relationships efficiently, potentially reducing N+1 query problems. It shows usage with `loadTreeRelationships()` and `toTree()`. ```php $users = User::tree(3)->get(); $users->loadTreeRelationships(); $users = User::tree(1)->get(); $tree = $users->loadTreeRelationships()->toTree(); ``` -------------------------------- ### Usage Outside of Laravel Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Explains how to enable support for common table expressions when using the package outside of a standard Laravel application or when package discovery is disabled. ```php class Post extends Model { use \Staudenmeir\LaravelCte\Eloquent\QueriesExpressions; } ``` -------------------------------- ### Reversing Custom Paths Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Demonstrates how to create reversed custom paths by setting the 'reverse' option to true within the getCustomPaths() method configuration. ```php class User extends Model { public function getCustomPaths() { return [ [ 'name' => 'reverse_slug_path', 'column' => 'slug', 'separator' => '/', 'reverse' => true, ], ]; } } ``` -------------------------------- ### Enabling Cycle Detection Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Details how to enable cycle detection in a model by overriding the enableCycleDetection() method to return true, preventing infinite loops in cyclic trees. ```php class User extends Model { public function enableCycleDetection(): bool { return true; } } ``` -------------------------------- ### Applying Query Constraints to CTEs in Laravel Adjacency List (PHP) Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Illustrates how to add custom constraints to both the initial and recursive parts of the Common Table Expression (CTE) used for graph traversal, demonstrating filtering inactive nodes and their descendants. ```php $descendants = Node::withQueryConstraint(function (Builder $query) { $query->where('nodes.active', true); }, function () { return Node::find($id)->descendants; }); ``` -------------------------------- ### Enable Cycle Detection Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Explains how to enable cycle detection in the graph to prevent infinite loops. This is crucial for graphs that may contain cyclical relationships. ```php class Node extends Model { public function enableCycleDetection(): bool { return true; } } ``` -------------------------------- ### Defining Custom Paths in Laravel Adjacency List (PHP) Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Demonstrates how to add custom path columns to query results by implementing the `getCustomPaths` method in the model and accessing the generated path on the result objects. ```php class Node extends Model { public function getCustomPaths(): array { return [ [ 'name' => 'slug_path', 'column' => 'slug', 'separator' => '/', ], ]; } } $descendantsAndSelf = Node::find(1)->descendantsAndSelf; echo $descendantsAndSelf[0]->slug_path; // node-1 echo $descendantsAndSelf[1]->slug_path; // node-1/node-2 echo $descendantsAndSelf[2]->slug_path; // node-1/node-2/node-3 ``` -------------------------------- ### Path Column Generation Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Demonstrates how the 'path' column is generated for ancestor, bloodline, descendant, and tree queries. It shows the dot-separated path from the parent to the model and how to access it. ```php $descendantsAndSelf = User::find(1)->descendantsAndSelf()->depthFirst()->get(); echo $descendantsAndSelf[0]->path; // 1 echo $descendantsAndSelf[1]->path; // 1.2 echo $descendantsAndSelf[2]->path; // 1.2.3 ``` -------------------------------- ### Adding Custom Paths Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Illustrates how to define custom path columns by overriding the getCustomPaths() method. This allows specifying a different column and separator for path generation. ```php class User extends Model { public function getCustomPaths() { return [ [ 'name' => 'slug_path', 'column' => 'slug', 'separator' => '/', ], ]; } } $descendantsAndSelf = User::find(1)->descendantsAndSelf; echo $descendantsAndSelf[0]->slug_path; // user-1 echo $descendantsAndSelf[1]->slug_path; // user-1/user-2 echo $descendantsAndSelf[2]->slug_path; // user-1/user-2/user-3 ``` -------------------------------- ### Generating Nested Tree Results Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Shows how to use the toTree() method on a collection of models to recursively structure them into a nested tree format, where each model has a 'children' attribute. ```php $users = User::tree()->get(); $tree = $users->toTree(); ``` -------------------------------- ### Limiting Ancestor Query Depth for Performance in Laravel Adjacency List (PHP) Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Demonstrates using `withMaxDepth()` with a negative value to set a minimum depth (maximum distance upwards) when querying ancestors, optimizing performance for ancestor traversals. ```PHP $ancestors = Node::withMaxDepth(-3, function () use ($id) { return Node::find($id)->ancestors; }); ``` -------------------------------- ### Ordering Graph Results Breadth-First or Depth-First in Laravel Adjacency List (PHP) Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Illustrates the use of `breadthFirst()` and `depthFirst()` query scopes to specify the traversal order when retrieving related nodes like descendants, controlling whether siblings or children are prioritized. ```PHP $descendants = Node::find($id)->descendants()->breadthFirst()->get(); $descendants = Node::find($id)->descendants()->depthFirst()->get(); ``` -------------------------------- ### Order Nodes Depth-First Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Demonstrates how to order nodes in a depth-first manner, prioritizing children over siblings. This is useful for traversing deep branches of the graph first. ```php $descendants = Node::find($id)->descendants()->depthFirst()->get(); ``` -------------------------------- ### Define Reversed Custom Paths Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Illustrates how to configure custom paths to be generated in reverse order. This is achieved by setting the 'reverse' option to true within the custom path definition. ```php class Node extends Model { public function getCustomPaths(): array { return [ [ 'name' => 'reverse_slug_path', 'column' => 'slug', 'separator' => '/', 'reverse' => true, ], ]; } } ``` -------------------------------- ### Reversing Custom Paths in Laravel Adjacency List (PHP) Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Shows how to reverse the order of elements within a custom path by adding the `'reverse' => true` option to the path definition array within the `getCustomPaths` method. ```php class Node extends Model { public function getCustomPaths(): array { return [ [ 'name' => 'reverse_slug_path', 'column' => 'slug', 'separator' => '/', 'reverse' => true, ], ]; } } ``` -------------------------------- ### Access Node Path Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Details how the `path` column is included in queries, representing the dot-separated path of local keys from the query's parent to the node. This helps in understanding the node's position in the hierarchy. ```php $descendantsAndSelf = Node::find(1)->descendantsAndSelf()->depthFirst()->get(); echo $descendantsAndSelf[0]->path; // 1 echo $descendantsAndSelf[1]->path; // 1.2 echo $descendantsAndSelf[2]->path; // 1.2.3 ``` -------------------------------- ### Query Constraints for CTEs Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Explains how to add custom constraints to the Common Table Expression (CTE) queries, both initial and recursive, using withQueryConstraint, withInitialQueryConstraint, or withRecursiveQueryConstraint. ```php $tree = User::withQueryConstraint(function (Builder $query) { $query->where('users.active', true); }, function () { return User::tree()->get(); }); ``` -------------------------------- ### Limiting Graph Query Depth for Performance in Laravel Adjacency List (PHP) Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Shows how to use the `withMaxDepth()` query scope to set a maximum depth for graph traversals, improving performance by only building the relevant section of the graph instead of the entire structure. ```PHP $descendants = Node::withMaxDepth(3, function () use ($id) { return Node::find($id)->descendants; }); ``` -------------------------------- ### Generating Nested Tree Structure in Laravel Adjacency List (PHP) Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Explains how to transform a flat collection of nodes retrieved from a graph query into a nested tree structure by calling the `toTree()` method on the collection. ```php $nodes = Node::find($id)->descendants; $tree = $nodes->toTree(); ``` -------------------------------- ### Accessing Node Path from Root in Laravel Adjacency List (PHP) Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Shows how to access the `path` column included in ancestor, descendant, and subgraph query results, which provides a dot-separated string representing the sequence of local keys from the query's parent to the node. ```PHP $descendantsAndSelf = Node::find(1)->descendantsAndSelf()->depthFirst()->get(); echo $descendantsAndSelf[0]->path; // 1 echo $descendantsAndSelf[1]->path; // 1.2 echo $descendantsAndSelf[2]->path; // 1.2.3 ``` -------------------------------- ### Depth Column and Constraints Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Describes the `depth` column included in query results for hierarchical data and how to use `whereDepth()` to filter by relative depth. It also introduces `withMaxDepth()` for performance optimization when limiting depth. ```php class User extends Model { public function getDepthName() { return 'depth'; } } $descendants = User::find($id)->descendants()->whereDepth(2)->get(); $descendants = User::find($id)->descendants()->whereDepth('<', 3)->get(); $descendants = User::withMaxDepth(3, function () use ($id) { return User::find($id)->descendants; }); $ancestors = User::withMaxDepth(-3, function () use ($id) { return User::find($id)->ancestors; }); ``` -------------------------------- ### Define Custom Paths for Node Models Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Demonstrates how to add custom path columns to model query results by defining a getCustomPaths method. This allows for generating hierarchical path strings based on specified columns and separators. ```php class Node extends Model { public function getCustomPaths(): array { return [ [ 'name' => 'slug_path', 'column' => 'slug', 'separator' => '/', ], ]; } } $descendantsAndSelf = Node::find(1)->descendantsAndSelf; echo $descendantsAndSelf[0]->slug_path; // node-1 echo $descendantsAndSelf[1]->slug_path; // node-1/node-2 echo $descendantsAndSelf[2]->slug_path; // node-1/node-2/node-3 ``` -------------------------------- ### Order Nodes Breadth-First Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Shows how to order nodes in a breadth-first manner, ensuring siblings are retrieved before children. This affects the traversal order of the graph. ```php $descendants = Node::find($id)->descendants()->breadthFirst()->get(); ``` -------------------------------- ### Override Path Separator Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Shows how to customize the path separator by implementing the `getPathSeparator()` method. This allows for flexibility in how the node path is represented. ```php class Node extends Model { public function getPathSeparator(): string { return '.'; } } ``` -------------------------------- ### Database Schema for Trees Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Defines a basic database schema for storing hierarchical data in a tree structure, including an ID and a nullable parent ID. ```php Schema::create('users', function (Blueprint $table) { $table->id(); $table->unsignedBigInteger('parent_id')->nullable(); }); ``` -------------------------------- ### Querying Subgraphs with Max Depth in Laravel Adjacency List (PHP) Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Shows how to use the `subgraph()` query scope with a second argument to limit the depth of the retrieved subgraph relative to the nodes defined by the constraint. ```PHP $subgraph = Node::subgraph($constraint, 3)->get(); ``` -------------------------------- ### Set Maximum Depth for Performance Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Explains how to use `withMaxDepth()` to set a maximum depth for queries, improving performance by only building the necessary part of the graph. Works with positive and negative depths. ```php $descendants = Node::withMaxDepth(3, function () use ($id) { return Node::find($id)->descendants; }); $ancestors = Node::withMaxDepth(-3, function () use ($id) { return Node::find($id)->ancestors; }); ``` -------------------------------- ### Retrieve Pivot Columns Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Demonstrates how to retrieve additional columns from the pivot table in a many-to-many relationship. This allows access to custom data associated with the relationship between nodes. ```php class Node extends Model { public function getPivotColumns(): array { return ['label', 'weight']; } } $nodes = Node::find($id)->descendants; foreach ($nodes as $node) { dump( $node->pivot->label, $node->pivot->weight ); } ``` -------------------------------- ### Filtering Graph Results by Relative Depth in Laravel Adjacency List (PHP) Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Demonstrates using the `whereDepth()` query scope to filter nodes in ancestor, descendant, or subgraph results based on their relative depth using comparison operators. ```PHP $descendants = Node::find($id)->descendants()->whereDepth(2)->get(); $descendants = Node::find($id)->descendants()->whereDepth('<', 3)->get(); ``` -------------------------------- ### Customizing Path Separator Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Shows how to override the getPathSeparator() method in a model to customize the separator used in the path column, defaulting to a dot ('.'). ```php class User extends Model { public function getPathSeparator() { return '.'; } } ``` -------------------------------- ### Generate Nested Tree Structure from Results Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Shows how to convert a collection of nodes, typically descendants, into a nested tree structure using the toTree() method. This method recursively organizes nodes by setting a 'children' relationship. ```php $nodes = Node::find($id)->descendants; $tree = $nodes->toTree(); ``` -------------------------------- ### Node Model with Graph Relationships Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Configures a Node model to use graph relationships by including the HasGraphRelationships trait and specifying the pivot table name. It also shows how to customize parent and child key names. ```php class Node extends Model { use \Staudenmeir\LaravelAdjacencyList\Eloquent\HasGraphRelationships; public function getPivotTableName(): string { return 'edges'; } public function getParentKeyName(): string { return 'source_id'; } public function getChildKeyName(): string { return 'target_id'; } public function getLocalKeyName(): string { return 'id'; } } ``` -------------------------------- ### Customizing Path Separator in Laravel Adjacency List (PHP) Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Implements the `getPathSeparator` method on the Node model to change the character used to separate local keys in the node path string. ```PHP class Node extends Model { public function getPathSeparator(): string { return '.'; } } ``` -------------------------------- ### Access Node Depth Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Explains how the `depth` column is included in ancestor, descendant, and subgraph queries, indicating the node's depth relative to the query's parent. Positive for descendants, negative for ancestors. ```php $descendantsAndSelf = Node::find($id)->descendantsAndSelf()->depthFirst()->get(); echo $descendantsAndSelf[0]->depth; // 0 echo $descendantsAndSelf[1]->depth; // 1 echo $descendantsAndSelf[2]->depth; // 2 ``` -------------------------------- ### Filter Nodes by Depth Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Shows how to use the `whereDepth()` query scope to filter nodes based on their relative depth. This allows for precise selection of nodes at specific levels. ```php $descendants = Node::find($id)->descendants()->whereDepth(2)->get(); $descendants = Node::find($id)->descendants()->whereDepth('<', 3)->get(); ``` -------------------------------- ### Adjusting Descendants Query with Intermediate Scopes Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Demonstrates how to modify descendant queries using methods like `withTrashedDescendants` and `withIntermediateScope` to filter or customize the results. ```php User::find($id)->recursivePosts()->withTrashedDescendants()->get(); User::find($id)->recursivePosts()->withIntermediateScope('active', new ActiveScope())->get(); User::find($id)->recursivePosts()->withIntermediateScope( 'depth', function ($query) { $query->whereDepth('<=', 10); } )->get(); User::find($id)->recursivePosts()->withoutIntermediateScope('active')->get(); ``` -------------------------------- ### Graph Relationship Schema Definition Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Defines the database schema for storing directed graphs using nodes and edges, suitable for many-to-many relationships like bills of materials or family trees. ```sql Schema::create('nodes', function (Blueprint $table) { $table->id(); }); Schema::create('edges', function (Blueprint $table) { $table->unsignedBigInteger('source_id'); $table->unsignedBigInteger('target_id'); $table->string('label'); $table->unsignedBigInteger('weight'); }); ``` -------------------------------- ### Filtering Models by Position Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Details the query scopes available for filtering models based on their position within the tree structure, such as `hasChildren()`, `hasParent()`, `isLeaf()`, and `isRoot()`. ```php $noLeaves = User::hasChildren()->get(); $noRoots = User::hasParent()->get(); $leaves = User::isLeaf()->get(); $leaves = User::doesntHaveChildren()->get(); $roots = User::isRoot()->get(); ``` -------------------------------- ### Customizing Path Name Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Explains how to override the getPathName() method in a model to change the default 'path' column name, useful when a 'path' column already exists in the table. ```php class User extends Model { public function getPathName() { return 'path'; } } ``` -------------------------------- ### Eloquent Model with Recursive Relationships Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Applies the HasRecursiveRelationships trait to an Eloquent model to enable recursive querying capabilities for tree structures. ```php class User extends Model { use \Staudenmeir\LaravelAdjacencyList\Eloquent\HasRecursiveRelationships; } ``` -------------------------------- ### Customizing Depth Column Name in Laravel Adjacency List (PHP) Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Implements the `getDepthName` method on the Node model to override the default column name used for the relative depth, useful if the table already has a column named 'depth'. ```PHP class Node extends Model { public function getDepthName(): string { return 'depth'; } } ``` -------------------------------- ### Override Path Column Name Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Demonstrates how to override the default `path` column name by implementing the `getPathName()` method. This is useful if your table already uses a different name for the path column. ```php class Node extends Model { public function getPathName(): string { return 'path'; } } ``` -------------------------------- ### Customizing Local Key Name Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Overrides the default local key name in an Eloquent model. This is useful when your primary key column is not named 'id'. ```php class User extends Model { public function getLocalKeyName() { return 'id'; } } ``` -------------------------------- ### Customizing Path Column Name in Laravel Adjacency List (PHP) Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Implements the `getPathName` method on the Node model to override the default column name used for the node path, useful if the table already has a column named 'path'. ```PHP class Node extends Model { public function getPathName(): string { return 'path'; } } ``` -------------------------------- ### Customizing Parent Key Name Source: https://github.com/staudenmeir/laravel-adjacency-list/blob/main/README.md Overrides the default parent key name in an Eloquent model. This is useful when your foreign key column is not named 'parent_id'. ```php class User extends Model { public function getParentKeyName() { return 'parent_id'; } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.