PHP code example of shopware / dbal-nested-set

1. Go to this page and download the library: Download shopware/dbal-nested-set library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

shopware / dbal-nested-set example snippets



use Shopware\DbalNestedSet\NestedSetConfig;

$config = new NestedSetConfig(
    'id', // Primary key column name
    'left', // left column name
    'right',  // right column name
    'level' // level column name
);

use Shopware\DbalNestedSet\NestedSetFactory;
use Doctrine\DBAL\Connection;

$writer = NestedSetFactory::createWriter($dbalConnection, $config);


$tableFactory = NestedSetFactory::createTableFactory($connection, $config);

$schema = new \Doctrine\DBAL\Schema\Schema();
$table = $tableFactory->createTable(
    $schema,
    'tree', // table name
    'root_id' // nested set root id
);
$table->addColumn('id', 'integer', ['unsigned' => true, 'autoincrement' => true]);
$table->addColumn('name', 'string', ['length' => 255]);
$table->setPrimaryKey(['id']);

$addSql = $schema->toSql($connection->getDatabasePlatform());


$writer = NestedSetFactory::createWriter($dbalConnection, $config);

// create a Root node
$writer->insertRoot('tree', 'root_id', 100, ['name' => 'Clothing']);

// create subnodes
$writer->insertAsFirstChild('tree', 'root_id', 1, ['name' => 'Men']);
$writer->insertAsNextSibling('tree', 'root_id', 2, ['name' => 'Women']);
$writer->insertAsFirstChild('tree', 'root_id', 2, ['name' => 'Suits']);
$writer->insertAsFirstChild('tree', 'root_id', 3, ['name' => 'Dresses']);
$writer->insertAsNextSibling('tree', 'root_id', 5, ['name' => 'Skirts']);
$writer->insertAsNextSibling('tree', 'root_id', 6, ['name' => 'Blouses']);
$writer->insertAsFirstChild('tree', 'root_id', 4, ['name' => 'Jackets']);
$writer->insertAsFirstChild('tree', 'root_id', 4, ['name' => 'Slacks']);
$writer->insertAsFirstChild('tree', 'root_id', 5, ['name' => 'Evening Gowns']);
$writer->insertAsNextSibling('tree', 'root_id', 10, ['name' => 'Sun Dresses']);

$writer->moveAsNextSibling('tree', 'root_id', 4, 7);

$inspector = NestedSetFactory::createTableNodeInspector($connection, $config);

$inspector->isLeaf('tree', 'root_id', 9); // true | false
$inspector->isAncestor('tree', 'root_id', 1, 2) // true | false

$queryFactory = NestedSetFactory::createQueryFactory($connection, $config);
$data = $queryFactory
            ->createChildrenQueryBuilder('tree', 't', 'root_id', 2)
            ->select('*')
            ->execute()
            ->fetchAll();