user1192304
user1192304

Reputation: 217

CakePHP - How to retrieve data from another model in controller

Currently i have 2 models. Users and Appbreak. They have associations of Users has many appbreak. Appbreaks belongs to users In my appbreak controller, there is a approve function which is called when a button from the view page is pressed.

In this function, i will need to update a value in the table of appbreak and a value in users table. I'm able to update value in appbreak by using the following:

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

However, i'm unable to pull the required data value from users table. <-- need to do so as i need to do some calculations before passing back the calculated value.

Am i able to get data from another model using the request method? Or do i need to use the find method? If i use the find method, am i able to update the the values and save it back into the database?

Upvotes: 4

Views: 10408

Answers (2)

Kiran
Kiran

Reputation: 921

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

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

To get data from AppBreak model use find method of
$this->AppBreak object
Similarly to get data for User use find method of
$this->User object

Upvotes: 7

swiecki
swiecki

Reputation: 3483

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

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

(as described here)

To save, simply create an array with at least the relevant record id. Include any fields you want to update, and then call the save method on the array like so:

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

Upvotes: 3

Related Questions