在本文中,我们将了解如何以编程方式在Magento 2中创建产品属性。如您所知,Magento 2通过EAV模型管理产品,因此我们不能通过添加产品表的列来简单地为产品添加属性。请阅读文章Magento 2 EAV模型以了解这一点。
在开始之前,请阅读文章Magento 2安装/升级脚本以了解如何创建模块安装类。
以编程方式添加产品属性的概述
- 第1步:创建文件InstallData.php
 - 第2步:定义install()方法
 - 第3步:创建自定义属性
 
在本文中,我们将使用Mageplaza HelloWorld模块来学习如何添加产品属性。
第1步:创建文件InstallData.php
 我们将从位于的InstallData类开始app/code/Mageplaza/HelloWorld/Setup/InstallData.php。此文件的内容: 
<?php
namespace Mageplaza\HelloWorld\Setup;
use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
class InstallData implements InstallDataInterface
{
	private $eavSetupFactory;
	public function __construct(EavSetupFactory $eavSetupFactory)
	{
		$this->eavSetupFactory = $eavSetupFactory;
	}
	
}
第2步:定义install()方法
<?php
	
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
	
}
第3步:创建自定义属性
以下是InstallSchema.php的所有行代码,用于以编程方式创建产品属性。
<?php
namespace Mageplaza\HelloWorld\Setup;
use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
class InstallData implements InstallDataInterface
{
	private $eavSetupFactory;
	public function __construct(EavSetupFactory $eavSetupFactory)
	{
		$this->eavSetupFactory = $eavSetupFactory;
	}
	
	public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
	{
		$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
		$eavSetup->addAttribute(
			\Magento\Catalog\Model\Product::ENTITY,
			'sample_attribute',
			[
				'type' => 'text',
				'backend' => '',
				'frontend' => '',
				'label' => 'Sample Atrribute',
				'input' => 'text',
				'class' => '',
				'source' => '',
				'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_GLOBAL,
				'visible' => true,
				'required' => true,
				'user_defined' => false,
				'default' => '',
				'searchable' => false,
				'filterable' => false,
				'comparable' => false,
				'visible_on_front' => false,
				'used_in_product_listing' => true,
				'unique' => false,
				'apply_to' => ''
			]
		);
	}
}
 如您所见,所有addAttribute方法都需要:
- 我们要添加属性的实体的类型ID
 - 属性的名称
 - 用于定义属性的键值对数组,例如组,输入类型,源,标签......
 
 全部完成后,请运行升级脚本php bin/magento setup:upgrade来安装模块,并sample_attribute创建产品属性。运行upgrade完成后,请运行php bin/magento setup:static-content:deploy并从管理员转到产品以检查结果。它将显示如下: 

如果要删除product属性,可以使用removeAttribute方法而不是addAttribute。它会是这样的:
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
        $eavSetup->removeAttribute(
          \Magento\Catalog\Model\Product::ENTITY,
           'sample_attribute');
    }
			