Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP: Retrieve specific table field in controller

Tags:

cakephp

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!

like image 543
ChrisDK Avatar asked Jul 29 '11 02:07

ChrisDK


1 Answers

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

like image 157
Ryan Avatar answered Oct 21 '22 07:10

Ryan