Jason McCreary
Jason McCreary

Reputation: 73001

CakePHP hasAndBelongsToMany (HABTM) Delete Joining Record

I have a HABTM relationship between Users and Locations. Both Models have the appropriate $hasAndBelongsToMany variable set.

When I managing User Locations, I want to delete the association between the User and Location, but not the Location. Clearly this Location could belong to other users. I would expect the following code to delete just the join table record provided the HABTM associations, but it deleted both records.

$this->Weather->deleteAll(array('Weather.id' => $this->data['weather_ids'], false);

However, I am new to CakePHP, so I am sure I am missing something. I have tried setting cascade to false and changing the Model order with User, User->Weather, Weather->User. No luck.

Thanks in advance for any help.

Upvotes: 4

Views: 6595

Answers (1)

deceze
deceze

Reputation: 522210

Not quite sure how Weather is related to your models, so I'll just go with the traditional names, LocationsUser is the joining table. This should delete all associations between the user with id $id and any locations:

$this->User->LocationsUser->deleteAll(array('LocationsUser.user_id' => $id), false);

Notice also that you're missing a closing bracket in your code snippet.

Upvotes: 7

Related Questions