CakePHP - 保存 HABTM
Posted
技术标签:
【中文标题】CakePHP - 保存 HABTM【英文标题】:CakePHP - Saving HABTM 【发布时间】:2014-02-10 01:11:47 【问题描述】:// 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 表中?
【问题讨论】:
官方文档中的如下链接你看过了吗:book.cakephp.org/2.0/en/models/… 是的,挑战在于保存一组 id。'Sector' => array( 'id' => array( (int) 0 => '2', (int) 1 => '3' ) )
【参考方案1】:
试试这个方法保存数据 $this->Model->saveAssociated($data); CakePHP Model saveAssociated
【讨论】:
saveAssociated() 方法对我不起作用。同样,它不喜欢 ID 数组。对我有用的是循环遍历 ID 数组并重建要关联的数组,然后在该新数组上执行 saveAll()。我认为有更好的方法来做到这一点 - 更多 CakePHPish,我只是不知道那是怎么回事。【参考方案2】:您的模型中的关系设置是否正确?您需要确保在Company
和Sectors
中都有HABTM。还要确保您的 HABTM 数据库表名称正确:companies_sectors
【讨论】:
以上是关于CakePHP - 保存 HABTM的主要内容,如果未能解决你的问题,请参考以下文章