【问题标题】:Magento 2 Add product to category (code)Magento 2 将产品添加到类别(代码)
【发布时间】:2017-05-23 07:48:08
【问题描述】:

我想通过他们的代码创建产品,并且我想将产品添加到类别中。
如何通过代码将产品添加到类别中?
我尝试将类别添加到产品 \Magento\Catalog\Model\Product,但没有方法 setCategory 或类似的方法。
然后我尝试将产品添加到类别Magento\Catalog\Model\Category,并且没有方法 addProduct 或类似的方法。 我看到了函数

CategoryLinkManagementInterface -> assignProductToCategories(
$product->getSku(),
$product->getCategoryIds() //but there is not categories yet
)

【问题讨论】:

    标签: categories magento2


    【解决方案1】:
        /**
         * @var \Magento\Catalog\Api\CategoryLinkManagementInterface
         */
        protected $_categoryLinkManagement;
    
    $this->_categoryLinkManagement->assignProductToCategories($sku, $categoryIds);
    //where $sku is sku of product, and $categoryIds is array of real categories ids
    

    【讨论】:

      【解决方案2】:

      您需要获取类别 ID 和产品 ID 来设置数据:这意味着:

      $this->getCategoryLinkManagement()->assignProductToCategories(
                      $product->getSku(),
                      $product->getCategoryIds()
                  );
      
      also impliment this function :
      
      private function getCategoryLinkManagement()
      {
          if (null === $this->categoryLinkManagement) {
              $this->categoryLinkManagement = \Magento\Framework\App\ObjectManager::getInstance()
                  ->get('Magento\Catalog\Api\CategoryLinkManagementInterface');
          }
          return $this->categoryLinkManagement;
      }
      

      你应该管理的其余依赖项:

      Magento\Catalog\Api\CategoryLinkManagementInterface

      intialize : protected $categoryLinkManagement;
      

      【讨论】:

      • 我遇到错误,无法将位置 0 的产品保存到类别 8
      【解决方案3】:
          $objectManager = ObjectManager::getInstance();
          $catalogProduct = $objectManager->create('Magento\Catalog\Model\Product');
          $catalogProduct->setSku('sku-1');
          $catalogProduct->setName('name');
          $catalogProduct->setAttributeSetId(4);
          $catalogProduct->setStatus(1); // Status on product enabled/ disabled 1/0
          $catalogProduct->setVisibility(4);
          $catalogProduct->setTypeId('simple'); // type of product (simple/virtual/downloadable/configurable)
          $catalogProduct->setPrice(100);
      
          $catalogProduct->setCategoryIds(['id']); // here you are
      
          $catalogProduct->setStockData([
              'is_in_stock' => true,
              'qty'         => 10
          ]);
      
          $catalogProduct->setStoreId(1); // $this->storeManagerInterface->getStore()->getId()
          $catalogProduct->setWebsiteIds([1]); // $this->storeManagerInterface->getStore()->getWebsiteId()
      
          $catalogProduct->save();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-18
        相关资源
        最近更新 更多