I am new to Cake and tried to find the best solution to retrieve a specific field belonging to an $id:
This is my view function in my Post controller
function view($id = null) {
if (!$id) {
$this->Session->setFlash(__('Invalid post', true));
$this->redirect(array('action' => 'index'));
}
$this->set('post', $this->Post->read(null, $id));
}
In the post table, there is a user_id foreign key. I need to retrieve this specific field belonging to this Post $id.
I read about functions as find('All), read() or just drop an unconventional session in the view through:
$session->write('example') = $post['Post']['user_id];
What is the best way to do this, my preference is to retrieve the field in the controller. Thanks!
CakePHP has a field function which should do just that.
$this->Post->id = $id;
$user_id = $this->Post->field('user_id');
For more information on using field, see: http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#model-field
A second option is to use the find function and returning only a few fields if you do not want the entire Post object. Also shown below is using a condition instead of setting the current Post.
$this->Post->find('first', array(
'conditions'=>array('id'=>$id),
'fields'=>array('user_id')
));
More information on find is available at: http://book.cakephp.org/2.0/en/models/retrieving-your-data.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With