Setup Graphs (Many-to-Many) with HasGraphRelationships
mainTo implement a graph structure where nodes can have multiple parents via a pivot table, use the HasGraphRelationships trait.
- Specify the pivot table name using
getPivotTableName(). - Customize parent/child keys using
getParentKeyName()andgetChildKeyName()(defaults areparent_idandchild_id). - Customize the local key using
getLocalKeyName(). - To access extra columns from the pivot table, override
getPivotColumns().
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 getPivotColumns(): array
{
return ['label', 'weight'];
}
}
// Accessing pivot data
$nodes = Node::find($id)->descendants;
foreach ($nodes as $node) {
dump($node->pivot->label, $node->pivot->weight);
}