Magento 将产品批量分配到类别

问题描述 投票:0回答:4

正如标题所说,我需要将产品批量分配到一个类别,并且从管理员那里我一次只能编辑一个产品;我不知道为什么从类别页面的“类别产品”选项卡中批量添加它们不起作用。
这就是为什么我需要另一种快速的方法,例如使用 phpMyAdmin 或类似的方法。

有什么帮助吗?

提前致谢!

php magento product categories mass-assignment
4个回答
10
投票

我创建了一个简单的脚本来在 Magento 之外执行此操作。请务必先在单个产品上进行测试,并确保它看起来符合您的预期。

// Load Magento
require_once 'path/to/app/Mage.php';
Mage::app();

// $productIds is an array of the products you want to modify.
// Create it however you want, I did it like this...
$productsIds = Mage::getModel('catalog/product')->getCollection()
    ->addAttributeToFilter('sku', array('like' => 'something'))
    ->getAllIds();

// Array of category_ids to add.
$newCategories = array(20);
foreach ($productIds as $id) {
    $product = Mage::getModel('catalog/product')->load($id);
    $product->setCategoryIds(
        array_merge($product->getCategoryIds(), $newCategories)
    );
    $product->save();
}

如果您想覆盖产品的现有类别,请将

array_merge(...)
更改为
$newCategories


6
投票

我会回避从数据库方面解决这个问题。如果您确实朝这个方向走,请确保进行大量备份,并在低使用率期间进行。

Magento 论坛上的以下主题也指出了同样的问题。一位发帖者通过示例推荐了原始 sql 方法。再次强调,我会小心 - 确保进行备份。

我最喜欢线程中的答案(由 Magento MVP 发布):

进入您不想要的类别,找到产品列表。 单击要删除的产品上的复选框并选择 从小下拉列表中删除。

现在进入您所在的类别 确实想要它们,请转到产品列表。选择“否”下拉列表,以便 显示不属于该类别的项目。你可能需要做一个选择性的 搜索限制内容并在几次迭代中完成。点击 选中复选框并告诉它添加内容。


2
投票

您也可以使用 magento API 来完成此操作 这是我用于批量添加产品的脚本。 sku.txt 每行包含一个 sku。

<?php
$wsdlUrl = "magento-root/index.php/api/soap/?wsdl";
$proxy = new SoapClient($wsdlUrl);
$sessionId = $proxy->login('apiuser', 'apipasswd');


$listOfDiscountedSKUFile = "sku.txt";


function readinFile($filePath)
{
    $fp = fopen($filePath,'r') or exit("Unable to open file!");
    $dataItems = array();
    while(!feof($fp))
    {
        $dataItems[] = trim(fgets($fp));
    }
    fclose($fp);
    var_dump($dataItems);
    return $dataItems;
}

function addToCategory($sku,$categoryId)
{
    global $proxy,$sessionId;
    $proxy->call($sessionId, 'category.assignProduct', array($categoryId, $sku));
}

function IsNullOrEmptyString($question){
        return (!isset($question) || trim($question)==='');
}
$categoryId = 82;//e.g.
$listOfSKU = readinFile($listOfDiscountedSKUFile);
foreach($listOfSKU as $sku)
{
    addToCategory($sku,$category);
}

?>

0
投票

我设法使用以下代码解决了该问题:

$write = Mage::getSingleton('core/resource')->getConnection('core_write');
$x = 1171;
$y = 2000;
$categoryID = 4;
$productPosition = 0;
while($x <= $y) {
$write->query("REPLACE INTO `catalog_category_product` (`category_id`, `product_id`,  `position`) VALUES ($categoryID, $x++, $productPosition)");
}
echo "The job is done";
?>

我希望每个人都清楚代码,如果不清楚,请回复,我会尽力解释。

@nachito:就是这里。

© www.soinside.com 2019 - 2024. All rights reserved.