Magento – How to assign associated products to a grouped product programatically in Magento2

grouped-productsmagento2product-linking

I have the following abridged code that I believe should assign a product to a grouped product; however when ran it doesn't create the assignment; that is – no entry is saved into the catalog_product_link table.

I've tried a few different ways (using the Data APIs/Interfaces) but have so far come up blank.

$obj = $this->_objectManager->create('\Magento\Catalog\Model\ProductFactory');

$product = $obj->create()->load(904); // productId of my grouped product

$product->setProductLinks([
    [
        "sku" => "group_sku",
        "link_type" => "associated",
        "linked_product_sku" => "simple_sku",
        "linked_product_type" => "simple",
        "position" => 1,
        "extension_attributes" => ["qty" => 1]
    ]
]);


$product->save();

Does anyone have any suggestions as to where I'm going wrong / or has anyone got a working code example?

Best Answer

I had the same problem trying to create related, upsell, cross-sell. I ended using something this:

$q = $this->_objectManager->get('\Magento\Framework\App\ResourceConnection');
$q->getConnection('core_write')->query("insert into catalog_product_link (linked_product_id, product_id,link_type_id) values (".$linked_product_id.",".$product_id.",".$link_type_id.")");

not the best way, I'm sure, but it works!.

Related Topic