ChrisDK
ChrisDK

Reputation: 243

CakePHP: Retrieve specific table field in controller

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!

Upvotes: 7

Views: 26574

Answers (4)

Warren Sergent
Warren Sergent

Reputation: 2597

In CakePHP 3, you can use $this->Model->get() to get the Entity, and then reference the required field directly.

$fieldValue = $this->ModelName->get($id)->fieldName;

Upvotes: 1

mmv_sat
mmv_sat

Reputation: 456

Try this one, since I don't know which field(s) you need I provide an example field array set using Magic Find Types:

$fields = ['title', 'body', 'created'];
$record = $this->Post->findById($id, $fields);

or multiple records

$recordSet = $this->Post->findAllByTitle('The title', $fields);

*Note the the second example doesn't make a lot of sense unless there are multiple titles with the name 'The title' in the the posts.title column.

Upvotes: 0

Ryan
Ryan

Reputation: 11776

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

Upvotes: 20

Anh Pham
Anh Pham

Reputation: 5481

$this->Post->id = $id;
$this->Session->write('example',$this->Post->field('user_id'));

Upvotes: 1

Related Questions