在Magento中,将单个属性分配给单个属性集是一个快速的过程,我们可以非常轻松地在后台管理完成。但是将大量属性分配给所有属性集(即,属性集大于25个)并不是一个快速的过程,需要花费很多时间。但是我们可以通过使用自定义脚本使过程变得非常简单。在这里,我将向您展示如何使用自定义脚本将产品属性分配给所有属性集。

将指定属性分配给任意单个属性集:

以下代码有助于使用属性代码和属性集名称将特定产品属性分配给任意特定属性集,

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
 
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('adminhtml');
 
/* Assign Specific Product Attribute to Any Single Attribute Set */
$attributeCode = 'size';
$attributeGroup = 'Product Details';
$attributeSet = 'Bag';
$eavSetup = $objectManager->create(\Magento\Eav\Setup\EavSetup::class);
$config = $objectManager->get(\Magento\Catalog\Model\Config::class);
$attributeManagement = $objectManager->get(\Magento\Eav\Api\AttributeManagementInterface::class);
 
$entityTypeId = $eavSetup->getEntityTypeId(\Magento\Catalog\Model\Product::ENTITY);
$attributeSet = $eavSetup->getAttributeSet($entityTypeId, $attributeSet);
if(isset($attributeSet['attribute_set_id'])) {
     $group_id = $config->getAttributeGroupId($attributeSet['attribute_set_id'], $attributeGroup);
     $attributeManagement->assign(
          'catalog_product',
          $attributeSet['attribute_set_id'],
          $group_id,
          $attributeCode,
          100
     );
}

为所有属性集分配指定属性:

以下代码将产品属性分配给所有属性集,

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
 
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('adminhtml');
 
/* Assign Specific Product Attribute to All the Attribute Sets */
$attributeCode = 'size';
$attributeGroup = 'Product Details';
 
$eavSetup = $objectManager->create(\Magento\Eav\Setup\EavSetup::class);
$config = $objectManager->get(\Magento\Catalog\Model\Config::class);
$attributeManagement = $objectManager->get(\Magento\Eav\Api\AttributeManagementInterface::class);
 
$entityTypeId = $eavSetup->getEntityTypeId(\Magento\Catalog\Model\Product::ENTITY);
$attributeSetIds = $eavSetup->getAllAttributeSetIds($entityTypeId);
foreach ($attributeSetIds as $attributeSetId) {
     if ($attributeSetId) {
          $group_id = $config->getAttributeGroupId($attributeSetId, $attributeGroup);
          $attributeManagement->assign(
               'catalog_product',
               $attributeSetId,
               $group_id,
               $attributeCode,
               100
          );
     }
}

希望这可以帮助到你。