Hello again,
I am stuck with the HABTM save/retrieval.. Please help.. I have got three
models.
1. Entitiy (id auto_increment)
2. User (id auto_increment)
3. Favorite(id auto_increment, entity_id)
A user can have many favorite entities and a favorite can belong to many
users.. so i have created a HABTM table users_favorites (user_id,
favorite_id).
I have defined the relationship as follows in the User Model.
var $hasAndBelongsToMany = array(
'Favorite' =>
array('className' => 'Favorite',
'joinTable' => 'users_favorites',
'foreignKey' => 'user_id',
'associationForeignKey' => 'favorite_id',
'conditions' => '',
'order' => '',
'limit' => '',
'unique' => false,
'finderQuery' => '',
'deleteQuery' => '',
'insertQuery' => ''
)
I provide an AJAX link to the user to favorite an entity like
http://<something.com>/users/favorite/entity_id.
In the users_controller, I have written teh following.
$user_id = $this->Auth->user('id');
$this->User->Behaviors->Attach(Behavior);
*save_data['User']['entity_id']=$entity_id;*
$this->User->save($save_data);
In the favorites behavior:
*function beforeSave($&model) {*
*$Favorite = new $Favorite;*
**
*if ($res = $Favorite->find($model->data['User']['entity_id'])) {*
*$id = $res['Favorite']['id'];*
*}*
*else {*
*$Favorite->save(array('id'=>"", 'entity_id' =>
$model->data['User']['entity_id']));*
*$id = $Favorite->getLastInsertID();*
*}*
*$model->data['Favorite']['id'] = $id;*
*}*
*}*
The above said code works quite well.. but my queries here revolove around
the hacks to get the HABTM working:
1. If i change $*save_data['User']['entity_id']=$entity_id; *to
$*save_data['Favorite']['entity_id']=$entity_id;
*and also at other places in the before save in the behavior, then weird
things happen.. now why would i want to set the user's field because
entity_id is actually a part of favorite model.
2. Why do i need to write a behavior to generate the linked model and then
fill the id. Isn't there some thing that does it automagically.. i am sure
that i am missing some thing...
Thanks in Advance.
--
Thanks & Regards,
Novice.
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"CakePHP" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at
http://groups.google.com/group/cake-php?hl=en
-~----------~----~----~----~------~----~------~--~---