1

我有关于商店、商店视图和网站创建的小问题。我在客户登记册上创建了商店(一个客户有一个网站、一个商店视图和一个商店),一切都很好,但是当保存例如商店视图时出现错误,数据库中的其他元素。

编码:

// Root Category
$category = new Mage_Catalog_Model_Category();
$category->setStoreId(0);
$category->save();

// Website
$website = new Mage_Core_Model_Website();
$website->setData(array(
    'code' => $codes,
    'sort_order' => 10
))->save();

// Create store group (store view)
$storeGroup = new Mage_Core_Model_Store_Group();
$storeGroup->setData(array(
    'website_id' => $website->getId(),
    'root_category_id' => $category->getId()
))->save();

// Create store
$store = new Mage_Core_Model_Store();
$store->setData(array(
    'code' => $codes,
    'website_id' => $website->getId(),
    'group_id' => $storeGroup->getId(),
));
$store->save();

我需要编辑代码,以便这些东西将在事务中创建并在出现错误时回滚。我不知道该怎么做,因为在每个对象保存后我都需要一个 id。

4

1 回答 1

2

好的,自己解决了

try {
    $write = Mage::getSingleton('core/resource')->getConnection('core_write');
    $write->beginTransaction();

    $category = Mage::getModel('catalog/category')
                    ->setStoreId(0)
                    ->setName($code)
                    ->setParentId(Mage_Catalog_Model_Category::TREE_ROOT_ID)
                    ->setPath(Mage_Catalog_Model_Category::TREE_ROOT_ID)
                    ->setDisplayMode(Mage_Catalog_Model_Category::DM_PRODUCT)
                    ->setIsActive(TRUE)
                    ->setId(NULL)
                    ->save();
    $website = Mage::getModel('core/website')
                   ->setCode($code)
                   ->setName($code)
                   ->setSortOrder(10)
                   ->setId(NULL)
                   ->save();
    $storegr = Mage::getModel('core/store_group')
                   ->setWebsiteId($website->getId())
                   ->setName($code)
                   ->setRootCategoryId($category->getId())
                   ->setId(NULL)
                   ->save();
    $store = Mage::getModel('core/store')
                 ->setCode('1'.$code)
                 ->setWebsiteId($website->getId())
                 ->setGroupId($storegr->getId())
                 ->setName($code)
                 ->setSortOrder(10)
                 ->setIsActive(TRUE)
                 ->setId(NULL)
                 ->save();
    $write->commit();
} catch (Exception $e) {
    $write->rollback();
}
于 2013-03-19T09:56:14.590 回答