I've been trying to save two foreign keys to the same row of a join table with no success. My Client
model has two HABTM association with both User
and Group
models, a user can have many clients and create clients under many different groups.
The UserClient join table looks like this:
+----+---------+----------+-----------+
| id | user_id | group_id | client_id |
+----+---------+----------+-----------+
| 1 | 1 | 1 | 1 |
| 2 | 1 | 2 | 2 |
| 3 | 3 | 4 | 3 |
+----+---------+---------+------------+
Client model:
public $hasAndBelongsToMany = array(
'User' => array(
'className' => 'User',
'joinTable' => 'UserClient',
'foreignKey' => 'client_id',
'associationForeignKey' => 'user_id'
),
'Group' => array(
'className' => 'Group',
'joinTable' => 'UserClient',
'foreignKey' => 'client_id',
'associationForeignKey' => 'group_id'
)
);
Client view:
<?php echo $this->Form->create('Client'); ?>
<fieldset>
<legend><?php echo __('Add Client'); ?></legend>
<?php
echo $this->Form->input('first_name');
echo $this->Form->input('last_name');
echo $this->Form->input('email');
echo $this->Form->input('phone');
echo $this->Form->input('Client', array('multiple'=> 'false', 'options' => $group_ids));
echo $this->Form->hidden('User', array('value' => $user_id));
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
This works to a point, however instead of saving user_id
, group_id
and client_id
to the same row in UserClient table, it create two separate rows for each HABTM, user_id
, client_id
get saved to one row and group_id
, client_id
get saved to another.
Is there any way to define multiple associationForeignKey
within the same HABTM association so user_id
, group_id
and client_id
get saved to the same row when creating a new client?
When you have to store additional fields in a HABTM
relation, it is sometimes easier to use a join model. In your case this would mean creating a model for your UserClient
table and use hasMany
relations instead of HABTM
.
Then of course you'll have to manage the save manually, but you'll have much more control of what must be done. You can find a few words about this in the Cake documentation.