Sharing technology, ideas, insights!
Call: +91 710 466 0336         Email: hello@sanisoft.com

Blog

unbindModel() and paginate() gotcha in CakePHP 1.2

A small note to myself regarding a gotcha which I ran into today morning with the built in unbindModel method which lets you disassociate model relations on the fly.

#1 Model->unbindModel() works only for the very next next operation of the model, well nothing new here it is written in the Book.

#2 $this->paginate() runs more than one operation on the model

So if you do something like

and then run a findAll() it works fine but if you do a $this->paginate() it gets all the associated models because after the first operation the bindings are again automagically put in place for you.

Of course there is a way to keep the unbind in place for the rest of the request – this is done by sending the second param to the unbindModel() as false. So your code would now look like

running paginate now works as expected.

The catch is that the book. mentions that the second param should be set to true for the unbind to persist through the rest of the request – so I am not sure if this is a bug in the code or a typo in to book, have edited the book as per the above, if the edit is accepted then I guess it was a typo…

Whatever the case – the thing to remember is that unbindModel will always need the second param for it to work with paginate()

About the Author

Dr. Tarique Sani is a pediatrician and forensic expert by education. He is a PHP programmer of 'wrote the book' caliber and has to his credit several very popular open source as well as commercial PHP projects. He leads a team of dynamic programmers at SANIsoft who have in-depth understanding of Web scalability, development tools and usability practices with strong developmental skills in PHP, MySQL/PostgreSQL, HTML, Javascript, and Linux/Apache

17 comments

  1. Just remember that if after the paginate() you want your associated models back, you will need to manually rebind them, since setting the $reset parameter to false in unbindModel() makes the unbinding permanent (not just for the paginate()).

  2. @keymaster – nice tip but in my experience usually not much is done after the paginate call in a given request. In the next request the binding will be again there.

Leave a Reply