In a controller/index action in my CakePHP2 app, I have
$this->Model-find('all',array( ... lots conditions and things... ));
Then, in controller/view I have:
$this->Model-find('first',array( ... lots conditions and things... ));
Both of these work really well, but I’m obviously repeating a large chunk of code (namely, the find conditions, field list etc) with the only two differences being that in the first one I’m doing find('all') and in the second one I’m doing find('first') and providing the id as one of the conditions.
Is there a way that I can move the conditions into the model and then run different types of find on those conditions?
You can create a method in Youur Model:
somewhere in this method just test if
(!empty($id))to return correct result. (You haven’t provide the ‘conditions and things’ so I can’t write the exact code here…and use it in both controler actions: