0

This has been causing me considerable grief for a couple of days now, so I turn to the community for help.

Assume two tables - Album HABTM Customer The join table is customer_albums PK(album_id, customer_id)

I have two controller functions:

public function like($album_id) {
 if ($this->request->is('post')) {
  $this->Album->CustomerAlbum->save(array('album_id' => $album_id,'customer_id' => $this->Auth->user('id')));
  $this->redirect(Controller::referer());

 }
}

and this one...

public function unlike($album_id) {
 $this->log($album_id);
 if ($this->request->is('post')) {
  $this->Album->CustomerAlbum->deleteAll(array('album_id' => $album_id,'customer_id' => $this->Auth->user('id'),false));
  $this->redirect(Controller::referer());

 }
}

The "Like" function results in the SQL:

INSERT INTO gre49302_digital.customer_albums (album_id, customer_id) VALUES (1, 62)

which is what I would expect.

However, the "Unlike" function results in:

SELECT CustomerAlbum.album_id FROM gre49302_digital.customer_albums AS CustomerAlbum WHERE album_id = 1 AND customer_id = 62

DELETE CustomerAlbum FROM gre49302_digital.customer_albums AS CustomerAlbum WHERE CustomerAlbum.album_id = (1)

Which indicates to me that CakePHP doesn't understand the concept of a compound primary key.

Consequently when attempting to delete one "like" between customer and album, I end up deleting everything for the selected album.

Ideally the "unlike" function should simply delete a single record from customer_albums using a compound primary key as selector.

Mark
  • 436
  • 4
  • 18
  • I have made some changes to the join table structure - removing the existing (compound) primary key and creating a new id INT pk. After having done this, Cake functions as per expectations on both delete and insert. The id INT pk is logically surplus to requirements, but seems to be requried to make Cake behave. Ideally I would like NOT to have to create this extra primary key, but it seems that the results can't be achieved without it at this stage. If anyone has any comments/thoughts - they would be much appreciated. – Mark Aug 25 '12 at 08:51

1 Answers1

-1

This could possibly be the cause. Your current code is:

deleteAll(array('album_id' => $album_id, 'customer_id' => $this->Auth->user('id'), false));

I'm going to assume you meant to set cascade to false. If that is the case, you have the wrong order of close parentheses.

Change your code to:

deleteAll(array('album_id' => $album_id, 'customer_id' => $this->Auth->user('id')), false);

Note the ('id')), false) vs ('id'), false)).

tigrang
  • 6,767
  • 1
  • 20
  • 22