Tuesday, May 1, 2012

Re: Saving HABTM erases existing records...

That is the default behaviour:

http://book.cakephp.org/2.0/en/models/saving-your-data.html#what-to-do-when-habtm-becomes-complicated

Jeremy Burns

On 1 May 2012, at 11:02:08, JonStark wrote:

Hello,

I currently having a problem achieving a follower system with HABTM.

In a word, my relationships seem to be well set up :

User HABTM Follower , and in my join table (users_uers) I have the tables  ID (auto increment) user_id and follower_id

I have a button "follow this user" :

<!--Follow-->
<?php 
echo $this->Form->create('User', array(
'action' => 'follow',
));

echo $this->Form->input('id', array(
'type' => 'hidden',
'value' => $user['User']['id'],
));
echo ("<input type='submit' class='btn btn-primary' value='Follow'>"); ?></td>
</form><!--End form-->

With this in the controller :

public function follow() {
        $this->User->set($this->data);
        if ($this->request->is('post')) {
        $this->request->data['Follower']['follower_id'] = $this->Auth->user('id');
        $this->User->save($this->request->data);
        $this->Session->setFlash(__('You are now following this user.'));
        $this->redirect(array('controller' => 'users', 'action' => 'index'));
        }
    }

I tough this would work ace, and it semmly did, but I have since understood that when saving a new relationship, Cake erases all previous existing one...

So if 1 followed by 3, when 3 follows 1 it erases the previous relation... In a word, it cannot work properly for a follower system.

I tough that adding the auto increment ID colums would prevent this, but I was wrong... so how can I save HABTM NEX relationships without erasing previous ones ? Is there a better solution for a follower system ? Thanks a lot.
 

--
Our newest site for the community: CakePHP Video Tutorials http://tv.cakephp.org
Check out the new CakePHP Questions site http://ask.cakephp.org and help others with their CakePHP related questions.
 
 
To unsubscribe from this group, send email to
cake-php+unsubscribe@googlegroups.com For more options, visit this group at http://groups.google.com/group/cake-php

No comments: