Joins In Magento 2

In this article we will learn magento2 mysql join queries.

The Syntax of Join is

$query = $salesRelatedProducts->getSelect()
                                        ->join(
                                            ['rpt' => 'sales_related_products_list'],
                                            'main_table.sales_id = rpt.sales_id'
                                        )->where("main_table.sales_id = 3");

echo $query->__toString();

in the above code we have called magento2 msql join function on our collection query object which takes two parameters first one is an array  table alias and second parameter is the condition at which it will join the tables, in the last I have printed the real sql query that is created, the output for above code is :

SELECT `main_table`.*, `rpt`.* FROM `pme_flash_sales` AS `main_table` INNER JOIN `sales_related_products_list` AS `rpt` ON main_table.sales_id = rpt.sales_id WHERE (main_table.sales_id = 3)

Hope this will help you in understanding how to write code for join queries in Magento2. Try the code above and in case you are not able to understand anything above please comment below.

Thanks 🙂 .

 

About Ejaz Alam

A Software Engineer who Believes in a simple lifestyle and follow a simple logic to make himself better than yesterday. :)

View all posts by Ejaz Alam →

Leave a Reply

Your email address will not be published. Required fields are marked *