0
// Models/Tables with HABTM:
companies, sectors, companies_sectors

// Controller
$sectors = $this->Sector->find('list', array('fields'=>array('Sector.id', 'Sector.sector')));

// View
echo $this->Form->input('Sector.id', array(
    'multiple' => 'checkbox',
    'options' => $sectors,
));

// Posted 
$this->request->data = array(
'Company' => array(
    'id' => '177',
    'company_name' => 'Testing Co',
),
'Sector' => array(
    'id' => array(
        (int) 0 => '2',
        (int) 1 => '3'
    )
));

// Controller
if ($this->request->is('post')) {

    // This saves the data into the 'companies' table just fine - but that's it
    $this->Company->save($this->request->data);
    
    // Tried this
    $this->Company->Sector->save($this->request->data);
    
    /* Get this error
     Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Array' in 'field list'
     SQL Query: UPDATE `h_dev`.`sectors` SET `id` = Array WHERE `h_dev`.`sectors`.`id` = '2' 
    */
    
    // Tried this - does nothing
    foreach ($this->request->data['Sector']['id'] as $id)
    {
        // made sure $this->Company->id is set from previous save()
        $this->Company->Sector->create();
        $this->Company->Sector->save(array('company_id'=>$this->Company->id, 'sector_id'=>$id));
    }
}

How do I save this request->data correctly into all HABTM tables?

Nimantha
  • 6,405
  • 6
  • 28
  • 69
  • 1
    Did you read the following link in the official documentation: http://book.cakephp.org/2.0/en/models/saving-your-data.html#saving-related-model-data-habtm – SaidbakR Feb 10 '14 at 01:15
  • Yes, the challenge is saving an array of ids. `'Sector' => array( 'id' => array( (int) 0 => '2', (int) 1 => '3' ) )` – user3287495 Feb 10 '14 at 02:33

2 Answers2

0

Try this method for saving data $this->Model->saveAssociated($data); CakePHP Model saveAssociated

beta-developper
  • 1,689
  • 1
  • 13
  • 24
  • The saveAssociated() method did not work for me. Again, it did not like the array of IDs. What did work for me was looping through the array of IDs and rebuilding the array to be associated, and then did a saveAll() on that new array. I think there's a better way of doing this - more CakePHPish, I just don't know how that is. – user3287495 Feb 11 '14 at 15:38
0

Do you have the relationships setup correctly in your models? You need to make sure that you have the HABTM in both Company and Sectors. Also be certain that your database table for the HABTM is named correctly: companies_sectors

Chuck Burgess
  • 11,600
  • 5
  • 41
  • 74