0

I have the following HABTM relationship:

 //Message.php
 class Message extends AppModel {
public $hasAndBelongsToMany = array(
    'User' => array(
        'className' => 'User',
        'joinTable' => 'messages_users',
        'foreignKey' => 'message_id',
        'associationForeignKey' => 'user_id',
        'unique' => true));
 }

 //User.php
 [...]
    public $hasAndBelongsToMany = array(
    'Message' => array(
        'className' => 'Message',
        'joinTable' => 'messages_users',
        'foreignKey' => 'user_id',
        'associationForeignKey' => 'message_id',
        'unique' => true));
 //[...]
 }

In my database I have these tables: users, messages and messages_users (with id, user_id and message_id fields).

I'm saving my data with:

//MessagesController.php
public function new_message() {
    $users = $this->Message->User->find('list', array(
        'fields' => array(
            'username')));
    $this->set(compact('users'));

    if ($this->request->is('post')) {
        //debug($this->request->data);
        if ($this->Message->saveAll($this->request->data, array(
            'deep' => true))) {
            $this->Session->setFlash('Message sent.');
            $this->redirect(array('action' => 'index'));
        }
    }
}

And debug info shows:

 array(
      'Message' => array(
           'users' => '1',
           'subject' => 'Subject',
           'text' => 'Text'
      )
 )

The data is saving without problems in the table messages, but the join table messages_users is empty. What am I doing wrong?

Thanks in advance!

MorbidDesign
  • 40
  • 12

1 Answers1

0

In order for data to be saved in the "join" table, you'll likely need some data for what you want your item(s) to actually be "join"ed to.

As an example, for your case, you probably want to add an array with some User data.

Recommended reading: http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasandbelongstomany-habtm

Dave
  • 28,833
  • 23
  • 113
  • 183
  • Hi Dave, thanks for your answer! I've read and re-read the book, but I still can't understand HABTM relationships... I just want to create a new message and link it with a created user, previously selected (via form) with a drop down list. I don't need to add new data to the user table. I need to link a new message with one (or more) created users. – MorbidDesign Feb 27 '14 at 18:07