0
votes
// 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?

StackOverflow is requiring that I put more details, even though I think I've been clear enough. So this is just filler text.

I think I got it! $save = array(); foreach ($this->request->data['Sector']['id'] as $id) { $save[] = array('Company'=>array('id'=>$this->Company->id), 'Sector'=>array('id'=>$id)); } $this->Company->Sector->saveAll($save); Unless someone knows a better, I think this will work.

2
Did you read the following link in the official documentation: book.cakephp.org/2.0/en/models/…SaidbakR
Yes, the challenge is saving an array of ids. 'Sector' => array( 'id' => array( (int) 0 => '2', (int) 1 => '3' ) )user3287495

2 Answers

0
votes

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

0
votes

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