Thursday, February 4, 2010

friends and self HABTM

I am trying to build a simple social network type site where a user
can friend another user. I realize this has been discussed before, a
lot, but none of the discussions on here really point out my issue so
I thought someone might be able to shine some light on where I am
going astray.

My user model

var $hasAndBelongsToMany = array(
'Friend' => array (
'className' => 'User',
'joinTable' => 'users_users',
'foreignKey' => 'user_id',
'associationForeignKey' => 'friend_id'
)
);

My users_controler addfriend fuction

function addfriend() {
if (!empty($this->data)) {
$user_id = $this->Auth->user('id'); // sets user_id in friend table
to authed user
//debug($this->data);exit;
if ($this->User->UsersUser->save($this->data))
{
$this->Session->setFlash(__('The User has been saved', true));
$this->redirect($this->referer());

} else {
$this->Session->setFlash(__('The User
could not be saved. Please, try again.', true));
debug($this->data);exit;
}
}
}

My old school form on the user/view page for adding a user just so i
can see whats going on for now
<form id="addfriend" method="post" action="/users/addfriend">
<fieldset style="display:none;"><input type="hidden" name="_method"
value="POST" /></fieldset>
<input name="data[Users_users][user_id]" type="text" value="<?
echo( $auth['User']['id']); ?>" id="user_id" />
<input name="data[Users_users][friend_id]" type="text" value="<?
echo( $user['User']['id']); ?>" id="friend_id" />

<?php echo $form->end('Submit');?>

I have a database table called users_users with an id, user_id, and
friend_id columns. When I manually input data everything works fine.
So I know my associations are proper.

However, when I submit my form with known good information nothing
goes into the database table. So I debuged the data that I am passing
to from the addfriend function and I get the following:

app/controllers/users_controller.php (line 402)

Array
(
[Users_users] => Array
(
[user_id] => 1
[friend_id] => 79
)

)


If anyone could point out what might be going wrong I would greatly
appreciate it.

Thanks.

Check out the new CakePHP Questions site http://cakeqs.org and help others with their CakePHP related questions.

You received this message because you are subscribed to the Google Groups "CakePHP" group.
To post to this group, send email to cake-php@googlegroups.com
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?hl=en

No comments: