I’m changing a relationship, in a CakePHP web application, from a belongsTo to a HABTM.
Originally we had a department table and a user table. The department table could contain many users; but a user could only belong to one department.
Now we want the ability for a user to belong to multiple departments. I created an intermediary table called departments_users and I filled it full of data.
I've modified the user model, and now I'm getting this error in the users view:
Notice (8): Undefined index: Department [APP/views/users/index.ctp, line 25]
This is the line of code in the view that is giving the error:
<?php
echo $this->Html->link($user['Department']['name'],
array('controller' => 'departments', 'action' => 'view', $user['Department']['id'])
);
?>
The above code uses the HtmlHelper to create a link with the name of the department (as the link text) and then supplies the department Id as a part of the link.
This is the code I've removed and added in the user model. First I removed this code from the $belongsTo relationship:
'Department' => array(
'className' => 'Department',
'foreignKey' => 'department_id'
),
Then I added this code in the $hasAndBelongsToMany relationship:
'Department' => array(
'className' => 'Department',
'joinTable' => 'departments_users',
'foreignKey' => 'user_id',
'associationForeignKey' => 'department_id',
'unique' => true
)
Could anyone tell what I could do to make this work? Thanks.