开发者

Can You Access Model Data in Controller in CakePHP?

开发者 https://www.devze.com 2023-01-16 14:45 出处:网络
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?

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开发者_Python百科' => 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!


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!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号