HABTM协会未保存 - cakephp

时间:2013-12-05 14:02:27

标签: cakephp save associations has-and-belongs-to-many

我一直在寻找所有类型的解决方案,但它无法正常工作。我有两个模型,Bredbook和Genre,在bredbook.php和genre.php,与HABTM相关联。无法保存关联。

以下是一个模型的代码:

public $hasAndBelongsToMany = array('Bredbook' => array('className' => 'Bredbook',
'joinTable' => 'bredbooks_genres',
'foreignKey' => 'genre_id',
'associationForeignKey' => 'bredbook_id'));

以下是表格:

echo $this->Form->create('Bredbook', array('action' => 'firstConnection'));
echo $this->Form->input('Genre', array('options' => $genres, 'empty' => false));
echo $this->Form->end('Validate');

在BredbooksController.php中:

if ($this->request->data)
{
    if($this->Bredbook->saveAssociated($this->request->data))
        return $this->redirect('/bredbooks/index');
}

bredbook的创建没问题,但是bredbooks_genres表中没有创建任何关联。我已经尝试了一切......欢迎任何帮助。

2 个答案:

答案 0 :(得分:0)

您需要在数据阵列中发送Bredbook.id

<?php
echo $this->Form->create('Bredbook');
//It can be any other attribute, but need some Breedbook data
echo $this->Form->input('Bredbook.id', array('value' => $id));
echo $this->Form->input(
    'Genre', 
     array(
        'options' =>$genres, 
        'empty' => false
    )
);
echo $this->Form->end('Validate');

或者在保存之前确保您的$this->request->data看起来与此类似:

Array
(
    [Bredbook] => Array
    (
         //It can be any other attribute, but need some Breedbook data
        [id] => 1
    )

    [Genre] => Array
    (
        [Genre] => Array
        (
             [0] => 1
        )

    )
)

只要您发送该模型的某些数据,此解决方案在您创建新Bredbook时也可以正常工作,它不需要是id,您也可以发送名称或Bredbook模型中的其他属性。如果您发送Bredbook.id,它将不会创建新记录并仅创建关联,但如果您不发送id并发送其他属性(例如name),它将会创建一条新记录,并将其与您发送的Genre数据相关联。

答案 1 :(得分:0)

我终于做到了:我不知道这是否是必要的,但我只是用蛋糕烘焙来生成所有东西:http://book.cakephp.org/2.0/en/console-and-shells/code-generation-with-bake.html

现在我需要做一些工作来重新安排所有视图,但我的保存工作正常,我首先发布的代码完全相同,而且我认为我节省了一些时间来处理所需的所有行为!

相关问题