Magento 2 将产品添加到类别(代码)

Magento 2 Add product to category (code)

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

CategoryLinkManagementInterface -> assignProductToCategories(
$product->getSku(),
$product->getCategoryIds() //but there is not categories yet
)
    /**
     * @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

您需要获取类别 Id 和产品 Id 才能设置数据:impliment this :

$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;
    $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();