2014-02-10 136 views
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)); 
    } 
} 

如何将此请求 - >数据正确保存到所有HABTM表中?CakePHP - 保存HABTM

StackOverflow需要我提供更多细节,尽管我认为我已经足够清楚了。所以这只是填充文本。

我想我明白了! $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); 除非有人知道更好,我认为这将起作用。

+1

您是否阅读了官方文档中的以下链接:http://book.cakephp.org/2.0/en/models/saving-your-data .html#saving-related-model-data-habtm – SaidbakR

+0

是的,挑战在于保存一个ID数组。 ' '扇区'=>数组( 'ID'=>数组( (INT)0 => '2', (INT)1 => '3' ) )' – user3287495

回答

0

尝试使用此方法保存数据$ this-> Model-> saveAssociated($ data); CakePHP Model saveAssociated

+0

的saveAssociated()方法做不适合我。同样,它不喜欢ID数组。对我有用的是循环访问ID数组并重建要关联的数组,然后在该新数组上执行saveAll()。我认为还有更好的方法 - 更多CakePHPish,我只是不知道那是怎么回事。 – user3287495

0

您是否在模型中正确设置了关系?您需要确保您在CompanySectors中都有HABTM。还要确保您的HABTM数据库表的名称是正确的:companies_sectors