Magento 2 : Join

Instantiate Collection :
protected $modelFactory;
public function __construct(
------------
\NameSpace\ModulueName\Model\ModelNameFactory $modelFactory, 
------------

) 
{
--------
$this->modelFactory = $modelFactory;
---------
}
Magento Left Join With Other Table
$collection = $this->modelFactory->create()->getCollection();

$collection->getSelect()->joinLeft(
        'othertablename',
        'othertablename.columnName = main_table.entity_id',
        array('othertableColumnName1','othertableColumnName2')
        )->where("main_table.columnName = $value");
Magento Left Join With more then one table
$collection = $this->modelFactory->create()->getCollection();
$collection
 ->getSelect()
 ->joinLeft(
     ['ot'=>'sales_order'],
     "main_table.order_id = ot.entity_id",
     [
         'increment_id' => 'ot.increment_id',
         'status' => 'GROUP_CONCAT(DISTINCT ot.state)'
     ]
 )
 ->joinLeft(
     ['ct' => 'customer_entity'],
     "main_table.customer_id = ct.entity_id",
     [
         "customer_name" => "ct.firstname"
     ]
 )
 ->group("main_table.order_id");
Magento Inner Join
$collection = $this->modelFactory->create()->getCollection();

$collection->getSelect()->join(
        'othertablename',
        'othertablename.columnName = main_table.entity_id',
        array('othertableColumnName1','othertableColumnName2')
        )->where("main_table.columnName = $value");
Magento Inner Join With more then one table
$collection = $this->modelFactory->create()->getCollection();

$collection
 ->getSelect()
 ->join(
     ['ot'=>'sales_order'],
     "main_table.order_id = ot.entity_id",
     [
         'increment_id' => 'ot.increment_id',
         'status' => 'GROUP_CONCAT(DISTINCT ot.state)'
     ]
 )
 ->join(
     ['ct' => 'customer_entity'],
     "main_table.customer_id = ct.entity_id",
     [
         "customer_name" => "ct.firstname"
     ]
 )
 ->group("main_table.order_id");

Comments