简体   繁体   中英

Populate table nested set Doctrine 1.2

I'm trying to populate a table set with more root Locations nested three levels: Region, Province and City.

the data to save them from an excel file I'm reading.

i write this script:

function importLocations()
{

    $objPHPExcel = PHPExcel_IOFactory::load("./data/elenco_comuni_italiani_30_giugno_2011.xls");

    $locationTable = LocationTable::getInstance();
    /* @var $tree Doctrine_Tree_NestedSet */
    $tree = $locationTable->getTree();

    $startRow = 2;
    $indexRegion = 0;
    $indexProvince = 2;
    $indexCity = 1;

    $objPHPExcel->setActiveSheetIndex($indexRegion);
    $objWorksheetRegion = $objPHPExcel->getActiveSheet();
    $highestRowRegion = $objWorksheetRegion->getHighestRow();
    $highestColumnRegion = $objWorksheetRegion->getHighestColumn();
    $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumnRegion);
    for ($rowRegion = $startRow; $rowRegion <= $highestRowRegion; ++$rowRegion) {
        $region_name = $objWorksheetRegion->getCellByColumnAndRow(0, $rowRegion)->getValue();
        $region_id = $objWorksheetRegion->getCellByColumnAndRow(1, $rowRegion)->getValue();
        // create a new root in the tree
        $tree->createRoot($nodeRegion = $locationTable->createNode($region_name));
        echo "\n\Process to Region: $region_name \n";
        //province
        $objPHPExcel->setActiveSheetIndex($indexProvince);
        $objWorksheetProvince = $objPHPExcel->getActiveSheet();
        $highestRowProvince = $objWorksheetProvince->getHighestRow();
        $highestColumnProvince = $objWorksheetProvince->getHighestColumn();
        $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumnProvince);
        for ($rowProvince = $startRow; $rowProvince <= $highestRowProvince; ++$rowProvince) {
            $province_name = $objWorksheetProvince->getCellByColumnAndRow(0, $rowProvince)->getValue();
            $province_code = $objWorksheetProvince->getCellByColumnAndRow(1, $rowProvince)->getValue();
            $province_region_id = $objWorksheetProvince->getCellByColumnAndRow(2, $rowProvince)->getValue();
            $province_id = $objWorksheetProvince->getCellByColumnAndRow(3, $rowProvince)->getValue();
            if ($province_region_id == $region_id) {
                //create province node and append it to the region
                $nodeProvince = $locationTable->createNode($province_name, $province_code);
                $locationTable->appendNode($nodeProvince, $nodeRegion);
                echo "Process to Province: $province_name \n";
                //city
                $objPHPExcel->setActiveSheetIndex($indexCity);
                $objWorksheetCity = $objPHPExcel->getActiveSheet();
                $highestRowCity = $objWorksheetCity->getHighestRow();
                $highestColumnCity = $objWorksheetCity->getHighestColumn();
                $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumnCity);
                for ($rowCity = $startRow; $rowCity <= $highestRowCity; ++$rowCity) {
                    $city_name = $objWorksheetCity->getCellByColumnAndRow(0, $rowCity)->getValue();
                    $city_province_id = $objWorksheetCity->getCellByColumnAndRow(1, $rowCity)->getValue();
                    $city_region_id = $objWorksheetCity->getCellByColumnAndRow(2, $rowCity)->getValue();
                    if ($city_region_id == $province_region_id && $city_province_id == $province_id) {
                        //create province node and append it to the region
                        $nodeCity = $locationTable->createNode($city_name);
                        $locationTable->appendNode($nodeCity, $nodeProvince);
                        echo "Process to City: $city_name \n";
                    }
                }
            }
        }
    }
    echo "Locations Salvate con Successo! \n\n\n";

}

and my LocationTable:

/**
 * LocationTable
 *
 * This class has been auto-generated by the Doctrine ORM Framework
 */
class LocationTable extends Doctrine_Table
{

    const LEVEL_REGION = '0';
    const LEVEL_PROVINCE = '1';
    const LEVEL_CITY = '2';

    /**
     * Returns an instance of this class.
     *
     * @return object LocationTable
     */
    public static function getInstance()
    {
        return Doctrine_Core::getTable('Location');
    }

    /**
     * Developer MUST CALL $parent->refresh() before insert a new node, otherwise
     * following insertions are wrong
     *
     * @param Location $son
     * @param Location $parent
     * @link http://trac.doctrine-project.org/ticket/928
     */
    public function appendNode(Location $son, Location $parent)
    {
        // internally calls save both on parent and son
        $son->getNode()->insertAsLastChildOf($parent);
        // load new parent lft and rgt values
        $parent->refresh();
    }

    /**
     * Build a tree node, save it and return it
     *
     * @param string $label
     * @param string $code
     *
     * @return Location
     */
    public function createNode($label, $code = null)
    {
        $node = $this->create(array('name' => $label, 'code' => $code));
        $node->save();
        return $node;
    }
}

my doctrine schema:

Location:
  tableName: locations
  actAs:
    NestedSet:
      hasManyRoots: true
      rootColumnName: root_id
  columns:
    id:
      type: integer(4)
      primary: true
      autoincrement: true
    name:
      type: string(255)
      notnull: true
    code:
      type: string(2)

the problem is that when I go to check a given node, we examine a province, if I perform a query like:

SELECT * FROM locations WHERE lft >= x AND rgt <= y

I can not find the city that I expect to find, but I find much more.

the scritp that reads excel file it works perfectly. I printed and read all the output and correct. I think there is something wrong in the lft and rgt values saved. You know you have found a few bugs in the documentation that is not prensa?

You have hasManyRoots set in your definition. That means, that your nested set table contains several trees. in each tree lft and rgt are built independent of other trees, so querying with SELECT * FROM locations WHERE lft >= x AND rgt <= y retrieves nodes from several trees.

You have two options to fix it: quick and right.

The quick one:

Every record has a root_id (set in rootColumnName attribute, it is also the default value) column. This column contains the id of the tree's root node. So, if you have to know the root_id of your desired node and use it like

SELECT * FROM locations WHERE lft >= x AND rgt <= y and root_id = rid

The right one:

Don't query the db directly. Fetch the desired record from the DB as object (eg with DQL ) and than traverse it using getChildren or getDescendants :

// Get the node into $provincevar
$all_cities_in_province = $province->getDescendants();

See NestedSet documentation for more detailed explanation.

And a little note: that might be a coincidence, absence of caching or something else, but it looks like Doctrine immidiately flushes changes made by NestedSet node manipulation functions (eg createRoot , delete , insertAsLastChildOf etc.). But that is my observation made on single machine with development environment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM