Hi Reader's,
Welcome to FindNerd,today we are going to discuss how to use joins with CakePhp in 2.x version?
Join is a very important feature for retrieving data from database with multiple tables. In a web application when we want to fetch multiple records from 3-4 tables then we should use join for fetching record because joins returns all records from 3-4 tables just on a single quires.
In other words we can say that joins are used for combining rows from two or more tables. joins commands are used for more complex queries in database management system.
You can see below example:
There are two tables, first table name is "User" and second table name is "UserProfile"
Now we want to fetch all records from both tables then firstly we will define join like below example:
<?php
$joins =array(
array(
'table' => 'users',
'alias' => 'User',/this is aliases
'type' => 'LEFT',
'conditions' => array(
'UserProfile.user_id = User.id',
)
),
);
?>
In above example we are fetching data from User table based on User.id which is also exist in UserProfile table.
So, Our query will like below:
<?php
$gymnastsList=$this->UserProfile->find('list',array('joins' => $joins,'conditions' => array('User.role'=>'Gymnast','User.account_status'=>'Active'), 'fields'=>array('User.id','UserProfile.full_name'),'order'=>'UserProfile.firstname' ));
?>
In above query we will find from User table User Role and User Status from User table and also get User full name from UserProfile table based on join query.
0 Comment(s)