1
votes

So quick overview of what I'm trying to do. User hasMany BusinessUnitsUser. BusinessUnit hasMany BusinessUnitUser.

In this manner, I've normalized their relationship to two hasManys (I hate working with HABTM related data).

On a new user form, I'd like to give the user the option of adding a new Business Unit at the same time.

Currently, my $this->request->data array looks like this:

Array
(
    [User] => Array
        (
            [title] => Mr
            [first_name] => Kyle
            [last_name] => O'Brien
            [username] => [email protected]
            [producing_office_id] => 4
        )

    [BusinessUnit] => Array
        (
            [name] => lskfjsldkfjsdlfk
        )

)

Now, this is obviously incorrect, but I'm struggling to think of how to resolve this. I thought giving you a visual of the array, you might be able to tell me what my array should look like.

Here's my relationship array in BusinessUnitsUser:

public $belongsTo = array(
        'User' => array(
            'className' => 'User',
            'foreignKey' => 'user_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        ),
        'BusinessUnit' => array(
            'className' => 'BusinessUnit',
            'foreignKey' => 'business_unit_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        )
    );

EDIT (thanks ndm)

Note the goal: I'm adding a user and I may or may not be adding BusinessUnitsUser associations as well but I'm definitely also going to be adding a new BusinessUnit - the form for which exists on the new_user form.

Currently, the User is saving with a $this->User->saveAll($this->request->data) but NOT the new BusinessUnit and certainly not the new BusinessUnitsUser entry (which I expect to contain the new user id and the new business unit id.

1
What makes you think that the given format is incorrect (it's not, given that I understood your setup correctly)? What's the actual problem?ndm
@ndm - well saving this data in a $this->User->saveAll($this->request->data); yeilds a newly saved user but no new entry for the BusinessUnit model and no new entry for the BusinessUnitsUser entry (which would have the new user_id and the new business_unit_id generated)Kyle O'Brien
Ok, I see, please add that to your question.ndm

1 Answers

1
votes

Save via the join table model

The solution should be pretty simple, for that type of association you'll have to save via the join table model (even if you don't save additional data on the that table):

$this->User->BusinessUnitsUser->saveAssociated($this->request->data);

See also http://book.cakephp.org/.../saving-your-data.html#saving-hasmany-through-data

That way the ORM can properly save the belongsTo associated data, and create an appropriate record in the join table, using foreign key values obtained from the save operations for the associated data.