Magento 2 how to create link_title column for the table catalog_product_link
-
28-03-2021 - |
Question
How to create column called link_title
to the catalog_product_link
table
& what are the steps, need to be followed to set the value to the respected column
Did small prototype as followed here but unable to save data.
<?php
ini_set('display_errors', '1');
ini_set('error_reporting', E_ALL);
use Magento\Framework\App\Bootstrap;
require __DIR__ . '/app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
$sourceMaterial='24-MB01';
$productLink = $objectManager->create('Magento\Catalog\Api\Data\ProductLinkInterface')
->setSku($sourceMaterial)
->setLinkedProductSku('24-MB06')
->setLinkTitle("helloworld")
->setLinkType('required');
$linkData[] = $productLink;
$product = $objectManager->create('Magento\Catalog\Api\ProductRepositoryInterface')->get($sourceMaterial);
if($product) {
$product->setProductLinks($linkData)->save();
}
?>
The recorded data is saving without link_title
value not saving.
Solution
For create link_title column
Create InstallSchema.php :
app/code/RH/Helloworld/Setup/InstallSchema.php
<?php
namespace RH\Helloworld\Setup;
use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
class InstallSchema implements InstallSchemaInterface {
/**
* {@inheritdoc}
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function install(SchemaSetupInterface $setup, ModuleContextInterface $context) {
$installer = $setup;
$installer->startSetup();
$eavTable = $installer->getTable('catalog_product_link');
$columns = [
'link_title' => [
'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
'nullable' => true,
'comment' => 'Link Title',
],
];
$connection = $installer->getConnection();
foreach ($columns as $name => $definition) {
$connection->addColumn($eavTable, $name, $definition);
}
$installer->endSetup();
}
}
For save record in custom column :
Inject this below code in your construct :
protected $productFactory;
public function __construct(
...
\Magento\Catalog\Model\ProductFactory $productFactory
...
) {
....
$this->productFactory = $productFactory;
....
}
And then, use this below code in your function :
$product = $this->productFactory->create()->load(45); //Set your product id here
$link = $product->getLinkInstance()->load(1); //Set your link id here
$link->setLinkTitle('test'); //Set your link title value here
$link->save();
Don't forget to execute this below command :
php bin/magento s:up
php bin/magento s:s:d -f
php bin/magento c:c
Hope, It will helpful for you.
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange