I have two tables, departments
and users
. On users
, I have the following fields:
id | username | password | email | department | date_created
Now on departments
, I have the following fields:
id | name
The department
field on the users
table is INT
and it points to the corresponding id
on the departments
table. How do I retrieve the corresponding name
to display on the department
field when rendered on the web? I tried doing this but it doesn't seem to work.
class UsersController extends AppController {
public function index() {
$this->set('users', $this->User->find('all'));
$departmentsArray = array();
$departments = $this->Department->find('all');
foreach ($departments as $department) {
$departmentsArray[$department['Department']['id']] = $department['Department']['name'];
}
$this->set('departments', $departmentsArray);
}
}
I am supposedly going to use it to retrieve the data on View\Users\index.ctp
. However, it gives me an error:
Error: Call to a member function find() on a non-object
File: D:\serveroot\app\Controller\UsersController.php
Line: 11
Line 11 is $departments = $this->Department->find('all');
from the first code block I gave above.
Sorry if this seems all too complicated, if there's a simpler way to approach this, please do tell me. I guess to put it simply, I need to retrieve data in a table via an id defined from another table.
EDIT:
Additional info from Hyarion, instead of using find('all')
I used find('list')
so I reduced the lines of code from 6 to 1! :) Here's the new code:
class UsersController extends AppController {
var $uses = array('User', 'Department');
public function index() {
$this->set('users', $this->User->find('all'));
$this->set('departments', $this->Department->find('list'));
}
}