Magento:在交易中存储,存储视图,网站

时间:2013-03-18 15:55:27

标签: php web e-commerce magento-1.7

我对商店,商店视图和网站创建存在小问题。我在客户注册表上创建商店(一个客户有一个网站,一个商店视图和一个商店),一切正常,但是在保存例如商店视图,DB中的其他元素时出错。

代码:

// 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。

1 个答案:

答案 0 :(得分: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();
}