0

我正在运行一个自动 php 导入文件以更新 Magento 2.2 中的所有产品。更准确地说,脚本会加载产品,然后,如果存在,则更新其信息并最终保存它。我的问题是:我尝试更新其元标题,但该方法根本不起作用。这是我的代码:

$product1 = $objectManager->get('Magento\Catalog\Model\Product')->getIdBySku($sku);
if($product1) {
    $pid=$product1;

    $product_n1=$objectManager->create('Magento\Catalog\Model\Product')->load($pid);
    $product_n1->setName(trim($importProduct[0])); // Name of product_n1
    $product_n1->setCategoryIds(array($category_id));
    $product_n1->setDescription(trim($descr));
    $product_n1->setShortDescription(trim($shortDesc));
    $metatitle =trim($importProduct[0]).' - Company name';
    $product_n1->setMetaTitle($metatitle);
    $metakey[]=$importProduct[0];
    $metakey[]= trim(preg_replace('/ +/', '', preg_replace('/[^A-Za-z0-9 ]/', '', urldecode(html_entity_decode(strip_tags($importProduct[0]))))));
    $metakey[]=trim(preg_replace('#[^0-9a-z]+#i', '-', $importProduct[0]));
    $meta_str=implode(',',$metakey);
    $product_n1->setMetaKeyword(trim($meta_str));
    $product_n1->setMetaDescription(trim(strip_tags($descr)));
    $product_n1->setStatus(1); // Status on product_n1 enabled/ disabled 1/0
    $product_n1->setWeight(10); // weight of product_n1
    $product_n1->setVisibility(4); // visibilty of product_n1 (catalog / search / catalog, search / Not visible individually)
    $product_n1->setTaxClassId(2); // Tax class id
    $product_n1->setPrice($importProduct[1]); // price of product_n1
    $product_n1->setStockData(
        array(
            'use_config_manage_stock' => 0,
            'manage_stock' => 1,
            'is_in_stock' => 1,
            'qty' => 1000,
            'min_sale_qty' => $pkgqty_int,
            'qty_increments' => $pkgqty_int,
            'enable_qty_increments' => 1
        )
    );

    $product_n1->save();
}

我不明白我的代码有什么问题。谢谢大家的支持

4

1 回答 1

0

您需要一个存储库来将产品保存在 magento 2.x 中

protected $productRepository;

public function __construct(
    \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
){
    $this->productRepository = $productRepository;
}

public function execute($id, $metaTitle) 
{
    $product = $this->productRepository->getById($id, true);
    $product->setMetatTitle($metaTitle);
    $product = $this->productRepository->save($product);
}
于 2018-06-05T17:02:40.177 回答