Fetching data from the database takes a lot time process. Eventually when you need to combine multiple tables in order to fetch the data, reducing database calls becomes very meaningful.
Although in CakePhp's model, by default if the association between various models either it be hasOne or belongsTo, hasMany can be done using find statement, as CakePHP will automatically use left joins and so with the sql statements for performing the DB calls.
So below we will discuss about the joins and fetching data using it.
The keys that define the joins are as follows:
1- table: The table for the join.
2- alias: An alias to the table or the name of the model associated
3- type: The type of join: inner, left or right.
4- conditions: The conditions to perform the join.
When using find() method, you can pass in option using 'joins' key to force a join statement below as an example:
$options['joins'] = array(
array('table' => 'books_tags',
'alias' => 'BooksTag',
'type' => 'inner',
'conditions' => array(
'Book.id = BooksTag.book_id'
)
),
array('table' => 'tags',
'alias' => 'Tag',
'type' => 'inner',
'conditions' => array(
'BooksTag.tag_id = Tag.id'
)
)
);
$options['conditions'] = array(
'Tag.tag' => 'Novel'
);
$books = $Book->find('all', $options);
Lastly, using joins allows you to have maximum flexibility in how CakePHP handles associations and fetches the data.
However, in most of the cases you can use other CakePhp methods to achieve the results such as by defining associations, binding models on the fly and using the Containable behavior.
0 Comment(s)