【问题标题】:Set attribute value in magento 2在magento 2中设置属性值
【发布时间】:2019-02-08 11:02:37
【问题描述】:

我以编程方式在 magento 2 中创建了名为 my_shipping_charge 的自定义属性。我为此属性设置了默认值“0”。当我创建新产品时它工作正常。但是,如果我想为已创建的产品设置此属性怎么办。?请帮我解决这个问题。

【问题讨论】:

标签: magento2


【解决方案1】:

对于已经创建的产品,我们应该手动更新,如果产品集合较大,可以在根目录下运行文件。 在这个根文件中,我们可以加载所有产品集合并为所有产品设置自定义属性值并保存。

根文件夹中的自定义文件如下所示:

<?php
use \Magento\Framework\App\Bootstrap;
require __DIR__ . "/app/bootstrap.php";
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$instance = \Magento\Framework\App\ObjectManager::getInstance();
$state = $objectManager->get('\Magento\Framework\App\State');
$state->setAreaCode('frontend');
$product_collections = $instance ->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collections = $product_collections->create();
$shippingCharge = "custom value";
foreach ($collections as $product) {
    $product->setMyShippingCharge($shippingCharge);
    $product->save();
}
?>

$shippingCharge 将是必须更新的自定义值。 在终端中运行根文件并重新索引。并从管理面板检查

【讨论】:

  • 我还找到了另一种更新属性的方法,使用导入。我为每个产品创建了一个 CSV 文件集属性值并导入该文件。它也有效。
  • 正确的想法,但更改目录 CSV 文件是有风险的,如果有多个商店或网站,请小心。
猜你喜欢
  • 1970-01-01
  • 2017-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多