6

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?

2

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!.

  • Only way that it work on grouped products for me.... – Lucas D.A.W. Feb 4 at 16:47
0

The data looks right, but you need to create an array of \Magento\Catalog\Model\ProductLink\Link objects and then pass that to setProductLinks rather than the data array.

I gave a full code example here: https://stackoverflow.com/a/40529460/2828129

0

The code below worked for me.

 $associated = array();
$position = 0;

foreach($childrenIds as $productId) {

    $position++;
    $productRepository = $objectManager->create('\Magento\Catalog\Api\ProductRepositoryInterface');
    $linkedProduct = $productRepository->getById($productId);
    $productLink = $objectManager->create('Magento\Catalog\Api\Data\ProductLinkInterface');
    $productLink->setSku($product->getSku())
        ->setLinkType('associated')
        ->setLinkedProductSku($linkedProduct->getSku())
        ->setLinkedProductType($linkedProduct->getTypeId())
        ->setPosition($position)
        ->getExtensionAttributes()
        ->setQty(1);

    $associated[] = $productLink;

}

$product->setProductLinks($associated);
$product->save();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.