zen of coding

LEFT JOIN vs INNER JOIN

By default, if you have a hasOne or belongsTo relationship between models, CakePHP will build a JOIN query using LEFT JOIN. In some cases, however, you would really prefer to do an INNER JOIN instead.

This is easily accomplished by specifying the ‘type’ key in your association.

So, for example, User hasOne Post:

var $hasOne = array(‘Post’=>array(‘type’=>’INNER’));

That’s all. Cake will now build a query using the INNER JOIN.

Remember that this key only works in the hasOne or belongsTo associations. If you would like to know how to force CakePHP to do JOIN for other types of associations, please take a look at this post.

  • bijan

    that’s cool man, saved a day. Thank ;)

  • @bijan

    Alrighty, cheers ;)

  • niknikav

    Thanks again for this hint! ;D

  • @niknikav

    No problemo ;)

  • thank for this … very cool …

  • @Klaus

    Glad it helped. You’re welcome.

  • Very useful, then now I am clear, I’ll use the default way LEFT JOIN.

%d bloggers like this: