CakePHP: getting a specific table field in the controller

I am new to Cake and tried to find the best solution for getting a specific field belonging to $ id:

This is my view function in 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)); } 

The message table has a foreign key user_id. I need to get this specific field belonging to this $ id post.

I read about functions like find ("Everything"), read (), or just throw an unconventional session in the form via:

 $session->write('example') = $post['Post']['user_id]; 

What is the best way to do this, I prefer to retrieve the field in the controller. Thanks!

+6
source share
3 answers

CakePHP has a field function that should do just that.

 $this->Post->id = $id; $user_id = $this->Post->field('user_id'); 

For more information about using a field, see http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#model-field

The second option is to use the find function and return only a few fields if you do not want the entire Post object. Also shown below, using a condition instead of setting the current message.

 $this->Post->find('first', array( 'conditions'=>array('id'=>$id), 'fields'=>array('user_id') )); 

Additional search information is available at: http://book.cakephp.org/2.0/en/models/retrieving-your-data.html

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

Try this because I don’t know which fields you need. I provide an example of an array of array fields using Magic Find types:

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

or several records

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

* Please note that the second example doesn’t make much sense if the posts.title header doesn’t have multiple titles with the title “Title”.

0
source

Source: https://habr.com/ru/post/893837/


All Articles