How to use left join SQL query in Model class Magento 2?

Magento 2 Left Join SQL query in resource model class to get data from multiple tables.

Left Join is used to fetch all records from the left table and retrieve matching records from the second table.

We can use joinLeft() method to use Left Join in Magento Collection.

A Demo to fetch customers with customer address details like city and postcode from the customer_address_entity table using the join query.

Defination of joinLeft():
joinLeft($name, $cond, $cols = ‘*’, $schema = null)

Here parameters data type,
* $name will be array|string|Zend_Db_Expr
* $cond string Join condition with other tables.
* $cols will be array|string. Columns to select from the joined table.
* $schema string. The database name to specify if any.

You can write a join operation on multiple tables also. SQL Query is not limited to only two tables relation.

You can do multiple joins between tables in a single query.

Some Brief explanation for the join query,

$customerCollection indicates the customer_entity table as the primary table.

$customerCollection->getSelect()->joinLeft(
           [‘ca’ => $this->getTable(‘customer_address_entity’)],
            ‘e.entity_id = ca.parent_id’,
            [‘ca.city’, ‘ca.postcode’]
);

The first parameter will be a table name to join with, ca is the alias for the customer_address_entity.
The second Parameter is the conditions to join with other table. //’e.entity_id = ca.parent_id’
The third parameter is the list of columns required from the second(Join) table.