:::: MENU ::::

Magento Tutorial | Magento Blog | Learn Magento 2

Cookies Consent Popup

            Try below code: 

           $obj = \Magento\Framework\App\ObjectManager::getInstance();    

            /** @var \Magento\Catalog\Model\Product $product */

            $productObject = $obj->get('Magento\Catalog\Model\Product');    

            $product = $productObject->loadByAttribute('sku', 'Test Test');    

            $linkDataAll = [];

            $skuLinks = "0012365,test1233,789456";

            $skuLinks = explode(",",$skuLinks);    

            foreach($skuLinks as $skuLink) {

                //check first that the product exist

                $linkedProduct = $productObject->loadByAttribute("sku",$skuLink);

                if($linkedProduct) {

                    /** @var  \Magento\Catalog\Api\Data\ProductLinkInterface $productLinks */

                    $productLinks = $obj->create('Magento\Catalog\Api\Data\ProductLinkInterface');

                    $linkData = $productLinks //Magento\Catalog\Api\Data\ProductLinkInterface

                        ->setSku($product->getSku())

                        ->setLinkedProductSku($skuLink)

                        ->setLinkType("related");

                    $linkDataAll[] = $linkData;

                }

            }

            if($linkDataAll) {

                print(count($linkDataAll)); //gives 3

                $product->setProductLinks($linkDataAll);

            }

            $product->save();

dont use **objectmanager** this code just for reference

Magento 2 introduced MSI (Multi‑Source Inventory) starting from version 2.3. This feature allows merchants to manage inventory across multiple sources (warehouses, stores, etc.). However, developers often need to programmatically fetch product inventory data, such as stock quantity and salable status, especially when building custom modules or integrations.

Problem Scenario

  • After enabling MSI, traditional methods like StockRegistryInterface may not return correct stock data.
  • Developers need to fetch salable quantity and is_salable status for products.
  • Custom modules or API integrations require accurate inventory values.

Solution: Use Magento MSI APIs

Magento provides new APIs and services to fetch inventory data under MSI. Below are examples:

1. Get Salable Quantity


use Magento\InventorySalesApi\Api\GetProductSalableQtyInterface;

class InventoryHelper
{
    protected $getProductSalableQty;

    public function __construct(
        GetProductSalableQtyInterface $getProductSalableQty
    ) {
        $this->getProductSalableQty = $getProductSalableQty;
    }

    public function getSalableQty($sku, $stockId = 1)
    {
        return $this->getProductSalableQty->execute($sku, $stockId);
    }
}

2. Check If Product is Salable


use Magento\InventorySalesApi\Api\IsProductSalableInterface;

class InventoryHelper
{
    protected $isProductSalable;

    public function __construct(
        IsProductSalableInterface $isProductSalable
    ) {
        $this->isProductSalable = $isProductSalable;
    }

    public function checkSalable($sku, $stockId = 1)
    {
        return $this->isProductSalable->execute($sku, $stockId);
    }
}

3. SQL View for Inventory Stock

Magento MSI creates database views like inventory_stock_1 to store inventory data. You can query directly:


SELECT product_id, sku, quantity, is_salable
FROM inventory_stock_1
WHERE sku = 'test-sku';

Practical Example

Suppose you want to display stock information on a custom product page. Using GetProductSalableQtyInterface, you can fetch the exact salable quantity for the SKU. Using IsProductSalableInterface, you can check if the product is available for purchase.

Best Practices

  • Always use MSI APIs instead of legacy StockRegistryInterface when MSI is enabled.
  • Use dependency injection to access MSI services.
  • Query inventory_stock_1 only for debugging, not in production code.
  • Test with multiple sources to ensure accurate results.

SEO & UX Benefits

  • Accurate stock data improves customer trust and reduces cart errors.
  • Helps SEO by ensuring products marked “In Stock” are truly available.
  • Improves conversion rates with reliable inventory visibility.

Troubleshooting

  • If MSI APIs return zero quantity, check if sources are assigned to the product.
  • Verify inventory_stock_1 view exists in the database.
  • Run php bin/magento indexer:reindex inventory after changes.
  • Check logs in var/log for MSI errors.

Conclusion

Magento 2 MSI changes how inventory data is managed. By using GetProductSalableQtyInterface and IsProductSalableInterface, developers can reliably fetch product stock information. This ensures accurate inventory display, better customer experience, and smoother integrations with external systems.

After upgrading Magento 2 to a newer version, many developers and store owners encounter indexing errors. These errors usually appear in the Admin Panel or when running CLI commands, and they can prevent catalog, price, or stock data from being updated correctly.

Common Error Messages


One or more indexers are invalid. Make sure your Magento cron job is running.

SQLSTATE[42S02]: Base table or view not found

Indexer process cannot be initialized.

Root Causes

  • Database schema changes after upgrade not applied correctly.
  • Missing or outdated indexer tables.
  • Cron jobs not running, leaving indexers invalid.
  • Custom modules conflicting with new Magento version.

Step-by-Step Fix

  1. Run Upgrade Command:
    
        php bin/magento setup:upgrade
        
  2. Recompile Code:
    
        php bin/magento setup:di:compile
        
  3. Reindex All:
    
        php bin/magento indexer:reindex
        
  4. Check Indexer Status:
    
        php bin/magento indexer:status
        
  5. Verify Cron Jobs:
    
        * * * * * php /path/to/magento/bin/magento cron:run | grep -v "Ran jobs by schedule" >> /path/to/magento/var/log/magento.cron.log
        

SQL Query Solution

If error in indexing after upgrade then run below SQL query in phpMyAdmin:


CREATE SQL SECURITY INVOKER VIEW `inventory_stock_1` AS 
SELECT DISTINCT 
    legacy_stock_status.product_id,
    legacy_stock_status.website_id,
    legacy_stock_status.stock_id,
    legacy_stock_status.qty quantity,
    legacy_stock_status.stock_status is_salable,
    product.sku
FROM `cataloginventory_stock_status` legacy_stock_status
INNER JOIN `catalog_product_entity` product 
    ON legacy_stock_status.product_id = product.entity_id;

After running the query, execute the following commands:

  • Reindex All:
    
        php bin/magento indexer:reindex
        

Practical Example

Suppose you upgraded from Magento 2.3.x to 2.4.x and see “One or more indexers are invalid.” Running the SQL query above recreates the missing inventory_stock_1 view, which resolves the indexing error. After clearing cache and recompiling, the indexers should show as Ready.

Best Practices

  • Always run setup:upgrade after upgrading Magento.
  • Reindex immediately after upgrade to refresh data tables.
  • Keep cron jobs active to avoid invalid indexers.
  • Document custom SQL fixes for future upgrades.

SEO & UX Benefits

  • Ensures product data is always fresh and accurate.
  • Improves customer experience with correct prices and stock levels.
  • Boosts SEO by keeping catalog data consistent.

Troubleshooting

  • If errors persist, check var/log/system.log and var/log/exception.log.
  • Verify database tables exist for all indexers.
  • Disable custom modules temporarily to isolate conflicts.
  • Run php bin/magento setup:db:status to confirm schema is up to date.

Conclusion

Indexing errors after upgrading Magento 2 are common but easily fixable. By running upgrade commands, applying the SQL query fix, and ensuring cron jobs are active, you can resolve these issues quickly. Keeping your store properly indexed ensures smooth performance, accurate product data, and a better shopping experience for customers.

When installing or running Magento 2.4.0, many developers encounter the error:


Could not validate a connection to Elasticsearch.
No alive nodes found in your cluster.

This error occurs because Magento 2.4.x requires Elasticsearch as the default catalog search engine. If Elasticsearch is not installed, not running, or misconfigured, Magento cannot connect and throws this error.

Root Cause

  • Elasticsearch service is not installed or not running.
  • Incorrect host or port configuration in Magento setup.
  • Firewall or permissions blocking the connection.
  • Version mismatch between Magento and Elasticsearch.

Step-by-Step Fix

  1. Install Elasticsearch: On Ubuntu/Debian:
    
        sudo apt update
        sudo apt install elasticsearch
        
    On CentOS/RHEL:
    
        sudo yum install elasticsearch
        
  2. Start and Enable Service:
    
        sudo systemctl start elasticsearch
        sudo systemctl enable elasticsearch
        
  3. Verify Elasticsearch is Running:
    
        curl -X GET "localhost:9200"
        
    You should see a JSON response with cluster information.
  4. Configure Magento to Use Elasticsearch: During installation, specify host and port:
    
        php bin/magento setup:install \
        --search-engine=elasticsearch7 \
        --elasticsearch-host=localhost \
        --elasticsearch-port=9200
        
  5. Check Magento Admin Settings: Go to Stores > Configuration > Catalog > Catalog Search and ensure Elasticsearch is selected with correct host and port.

Version Compatibility

  • Magento 2.4.0 supports Elasticsearch 7.x.
  • Ensure you install Elasticsearch 7.x or higher for compatibility.

Best Practices

  • Always run Elasticsearch as a service and enable auto‑start.
  • Use proper memory allocation for Elasticsearch (edit jvm.options).
  • Secure Elasticsearch if exposed to public networks.
  • Test connection with curl before running Magento setup.

Troubleshooting

  • If you still see “No alive nodes found,” check logs in /var/log/elasticsearch.
  • Ensure port 9200 is open and not blocked by firewall.
  • Restart both Elasticsearch and Apache/Nginx services after changes.
  • Check PHP memory limits if installation fails.

Conclusion

The “Could Not Validate a Connection to Elasticsearch” error in Magento 2.4.0 is caused by missing or misconfigured Elasticsearch. By installing Elasticsearch, starting the service, and configuring Magento correctly, you can resolve the issue and proceed with installation. Keeping Elasticsearch properly maintained ensures smooth catalog search and overall store performance.