0

CakePHP: ungreedy grabbing

Posted October 23rd, 2006 in Programming by Olexandr Melnyk

Sometimes it takes a while to solve simple problems.

A while ago, when working on a project in CakePHP, I needed to set up more complex fetching rules than just changing recursion depth. Fortunately, CakePHP offered such flexibility.

Say, we have such relations schema:

Team hasMany Coach, Player
Coach, Player hasMany Hobby

And we want to grab team info with its coaches and their hobbies and its players (without hobbies). What I first though of was:

$this->Team->recursion = 2;
$this->Player->unbindModel(
    array( 'hasMany' => 
             array( 'Hobby' )
          )
);
$team = $this->Team->findById($id);

But it didn’t work. I’ve been trying different code variations until I found the right one:

$this->Team->recursion = 2;
$this->Team->Player->unbindModel(
    array( 'hasMany' => 
             array( 'Hobby' )
          )
);
$team = $this->Team->findById($id);

Notice the Team between $this and Player.

Share and Enjoy:
  • Facebook
  • VKontakte
  • MySpace
  • LinkedIn
  • Twitter
  • Identi.ca
  • Tumblr
  • Digg
  • Reddit
  • del.icio.us
  • StumbleUpon
  • Google Bookmarks
  • Google Buzz
  • Live
  • Technorati
  • HackerNews
  • Slashdot
  • Hyves
  • Tuenti
  • PDF
blog comments powered by Disqus