Free Android CakePHP GMaps Articles by Bali Web Design

July 31, 2009

Forcing inner join on belongTo and hasOne

Filed under: php — Tags: — admin @ 2:13 am

By default, belongsTo and hasOne using LEFT JOIN relation between parent and child table or model. We can forcing the relationship to use either INNER JOIN or LEFT JOIN based on our need. Cakephp has add new option when binding model, name type: value is LEFT or INNER.

For example we have parent table Author and hasOne Post, we can set INNER JOIN relation by default on model class or in controller using bindModel. In this example the hasOne relation set on model class

<?php
class Author extends AppModel {
var $name = ‘Author’;
var $hasOne = array(’Post’=>array(’type’=>’INNER’));
}
?>

and running on controller

$this->Author->find(‘all’);

cakephp will generate query for author table.

SELECT `Author`.`id`, `Author`.`name`, `Post`.`id`, `Post`.`post_id`, `Post`.`title` FROM `authors` AS `Author` INNER JOIN `posts` AS `Post` ON (`Post`.`post_id` = `Author`.`id`) WHERE 1 = 1


1 Comment »

  1. How I force Inner Join in HABTM?!

    Comment by Wallace — December 27, 2011 @ 6:20 am

RSS feed for comments on this post. TrackBack URL

Leave a comment