views:

23

answers:

1

This is probably a dumb question, but I can't find a definitive answer anywhere. Is it possible to access model data in a Controller, and if so, how?

I tried the following:

$this->set('mydata', $this->Model->find('all', 'conditions' => array('id' => 'someID')));

And accessing it via this in the controller:

$mydata['Model']['field']

But that appears to only be for the views.

Is there a way to access the model data in the controller? The reason is that I need to perform calculations on an associated model (belongsTo) that can't be done via hidden fields or anything because the ID of the associated model isn't passed until after the form is submitted.

Any help would be greatly appreciated!

A: 

Hmm, how about:

$myData = $this->Model->find('all', 'conditions' => /* ... */);

$myData['Model']['field'];
$myData['RelatedModel']['field'];

$this->set('mydata', $myData);

Simple enough :)

Model::find() returns your data, you don't need to pass it directly to Controller::set(), you can mess with it first and then pass it on to your views.

But, I'd advise against it, it's better if you have a Model::messWithData($data) and let models deal with data, and let controllers take care of application logic. Remember, fat models, skinny controllers!

dr Hannibal Lecter
Thanks for the response! What I'm trying to do is perform a calculation that uses a bit of data from the form submission and mixes it with data from an associated belongsTo model. You're saying that I should have a function in the associated model that performs the calculation and then just call it in the controller?
Justin
Depends on what you're trying to do, but my answer is essentially "yes". :) It is better to keep your data-altering stuff in your models (that is their purpose!), unless it's something you're only going to display in the view (i.e. if it's only a formatting issue - in that case, I'd use a custom helper which would prepare the data for display).
dr Hannibal Lecter
Thanks- I've started implementing this across the entire project and it definitely makes the code a lot more readable to have all the DB queries in the models!
Justin
Glad I could help :) Teknoid wrote a simple explanation for this principle: http://nuts-and-bolts-of-cakephp.com/2008/05/05/fatten-up-your-models/ but if you look it up on Google, there are plenty of other tips and articles for cake coding styles :)
dr Hannibal Lecter

related questions