Focus on IT Recommend

Home > has and belongs to many - CakePHP hasAndBelongsToMany (HABTM) Delete Joining Record

has and belongs to many - 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('' => $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.

cakephp has-and-belongs-to-many
asked May 15 '10 at 2:53 Jason McCreary 48.8k 15 84 135


1 Answers


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:

Recommend:has and belongs to many - CakePHP HABTM question

ree time. For starters I want to add multiple tags to multiple photos. I have a tags model and mot model (the photos). Snip of mot model: var $hasAndBelongsToMany = array( 'Tag' =>

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

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

answered May 15 '10 at 5:00 deceze ♦ 320k 50 415 559 1   Yes, sorry, the model is actually Weather locations and I used them interchangeably. Your code was spot on, I didn't realize I could reference the association Model. Here's what I had for completeness. Works just right! $this->User->UsersWeather->deleteAll(array('UsersWeather.wea‌​ther_id' => $this->data['weather_ids'], 'UsersWeather.user_id' => $this->user['User']['id'])) –  Jason McCreary May 15 '10 at 17:06


Recommend:has and belongs to many - Need help with hasAndBelongsToMany (HABTM) Cakephp find

the SQL query being run is not doing a Join on the many to many table. I have a users table, projects table, and users_projects table. I want to get a list of all projects a user is associated with in a separate Allocations controller. I h

------splitte line----------------------------