Magento 2 – Add Attribute to Multiple Attribute Sets Programmatically

attribute-setattributeseavmagento2product-attribute

Subject. Which classes I need to use to deal with it?

It seems that I don't understand much about how attributes work.

For example I use this code to add attribute to one attribute set and to one attribute group:

/** @var $attribute \Magento\Catalog\Model\ResourceModel\Eav\Attribute */
$attribute->setAttributeSetId($attributeSetId);
$attribute->setAttributeGroupId($groupId);

Thanks.

UPD:
My problem not in 'how to get attribute set ids', I already have a few. I'm more interesting in the part of code where // add your code here.
I think if we set the value by method $attribute->setAttributeSetId(), it override previous attribute set link in the attribute. I'm trying to find some solution like $attribute->addAttributeSetId() or $attribute->setAttributeSetIds(), but there are none

UPD2:
Found the way: Using \Magento\Eav\Api\AttributeManagementInterface->assign(). Full code in answer below.

Best Answer

Found a simple solution.

my method:

public function assignAttributeToSets($attribute_code, $attribute_set_ids) {
    foreach ($attribute_set_ids as $set_id) {
        $group_id = $this->config->getAttributeGroupId($set_id, 'Product Details');
        $this->attributeManagement->assign(
            'catalog_product',  // entity type code
            $set_id,
            $group_id,
            $attribute_code,
            null
        );
    }
}

And constructor:

public function __construct(
    \Magento\Catalog\Model\Config $config,
    \Magento\Eav\Api\AttributeManagementInterface $attributeManagement
)
{
    $this->config = $config;
    $this->attributeManagement = $attributeManagement;
}