CakePHP - How to get data from another model in the controller

I currently have 2 models. Users and Appbreak. They have associations. Users have many applications. Appbreaks belongs to users. In my appbreak controller there is an approving function that is called when a button is clicked from the watch page.

In this function, I will need to update the value in the appbreak table and the value in the users table. I can update the value in appbreak using the following:

$this->Appbreak->id = $id; $this->Appbreak->set('approve', 'Yes'); $this->Appbreak->save(); 

However, I cannot get the required data value from the users table. <- it is necessary to do this, since I need to perform some calculations before passing back the calculated value.

Is it possible to get data from another model using the query method? Or do I need to use the find method? If I use the find method, can I update the values ​​and save them back to the database?

+4
source share
2 answers

Use find () to get your values, and if you need to update the values, use save (). For instance:

 $this->Appbreak->Users->find('first', $params); 

(as described here )

To save, just create an array with at least the corresponding record identifier. Include all the fields you want to update, and then call the save method in the array as follows:

 $data = array('id' => 10, 'title' => 'My new title'); // This will update Recipe with id 10 $this->Recipe->save($data); 
+3
source

You can use any number of models in the controller. Declare an array 'uses' in the controller

 <?php class DemoController extends AppController{ public $uses=array('Appbreak','User'); } ?> 

To get data from the AppBreak model, use the find method to search for the $this->AppBreak object
Similarly, to retrieve data for User , use the find method to search for the $this->User object

+6
source

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


All Articles