如何通过Magento中的控制器将数组中的多个数据插入数据库

时间:2016-12-22 04:31:21

标签: php mysql magento

我的数据库中有costum表名test_category,其中包含列:

entity_id(主键和自动增量),category_idcategory_name

我将类别数据存储在数组中,我想通过magento中的控制器将其插入数据库,有没有办法在数组中插入数据

Array
(
    [category_id] => Array
        (
            [0] => 13361
            [1] => 13697
            [2] => 13755
            [3] => 13760
        )
    [category_name] => Array
        (
            [0] => Baby & Toddler
            [1] => Baby & Toddler - Baby Gear
            [2] => Baby & Toddler - Baby Gear - Backpacks & Carriers 
            [3] => Baby & Toddler - Baby Gear - Backpacks & Carriers  - Accessories
        )
)

1 个答案:

答案 0 :(得分:0)

<?php
require_once dirname(__FILE__) . '/app/Mage.php';
Mage::app()->setCurrentStore(Mage::getModel('core/store')->load(Mage_Core_Model_App::ADMIN_STORE_ID));

// Your data array
$catarr = array ( 
        'category_id' => array (13361,13697,13755,13760),
        'category_name' => array('Baby & Toddler','Baby & Toddler - Baby Gear','Baby & Toddler - Baby Gear - Backpacks & Carriers','Baby & Toddler - Baby Gear - Backpacks & Carriers  - Accessories')
       );

$combineArr = array_combine($catarr['category_id'],$catarr['category_name']);   
echo '<pre>';
print_r($catarr);   
print_r($combineArr);   
echo '</pre>';

// set your parent category
$parentId = '2';

foreach($combineArr as $combineArrKey => $combineArrVal) {
    try{
        $category = Mage::getModel('catalog/category');
        $category->setName($combineArrVal);
        //$category->setId($combineArrKey);
        //$category->setUrlKey('your-cat-url-key');
        $category->setIsActive(1);
        $category->setDisplayMode('PRODUCTS');
        $category->setIsAnchor(1); //for active anchor
        $category->setStoreId(Mage::app()->getStore()->getId());
        $parentCategory = Mage::getModel('catalog/category')->load($parentId);
        $category->setPath($parentCategory->getPath());
        $category->save();
    } catch(Exception $e) {
        echo $e->getMessage();
        echo '<br />';
    }
}

?>

您可以将此文件放在根文件夹中并运行。如果你想在你的控制器中使用它,而不是删除前2行代码行。

如果您想使用与使用

相同的类别ID
$category->setId($combineArrKey);