Cakephp Left Join Query


Cakephp Left Join Query : Join is an important part for getting data collectively from two or more than two table. We pass the type parameter as “LEFT” for left joins. Here in this tutorial we are going to explain the LEFT JOIN with example in cakephp framework. We will use cakephp model syntax for LEFT JOIN in Cakephp.


Cakephp Left Join Query

Suppose we have a model called User which is associated with user table. Here in this example we are going to LEFT JOIN this table with profile table which has user_id as foreign key.

Cakephp Left Join Query Example with syntax


Cakephp Left Join Query Example

   $userProfile = $this->User->find('all',
                array('joins' => array(
                                       array('table' => 'profile',
                                             'alias' => 'p',
                                             'type' => 'LEFT',
                                             'foreignKey' => false,
                                             'conditions'=> array('user.id = p.user_id')                                             
                                        )
                                 ),
                 
                ));

The above example will LEFT JOIN the two tables. it will generate the mysql query something like this –

Query Generated : SELECT user.id, user.name, user.email, user.phone FROM user LEFT JOIN p on (user.id = p.user_id)

Advertisements

Add Comment

📖 Read More