// 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);
除非有人知道更好,我认为这将起作用。
您是否阅读了官方文档中的以下链接:http://book.cakephp.org/2.0/en/models/saving-your-data .html#saving-related-model-data-habtm – SaidbakR
是的,挑战在于保存一个ID数组。 ' '扇区'=>数组( 'ID'=>数组( (INT)0 => '2', (INT)1 => '3' ) )' – user3287495