CakePHP Automagic Form Helper with Associations

时间:2012-01-24 13:40:51

标签: php cakephp form-helpers

我有两个CakePHP模型,测试和问题,其中一个测试有很多问题,一个问题只有一个测试。

这段代码都没有:

echo $form->create("Question", array('action' => 'add'));
echo $form->input("text");
echo $form->input("Test.id", array( 'value' => $test['Test']['id']  , 'type' => 'hidden') ); 
echo $form->end("Add");

也:

echo $form->create("Question", array('action' => 'add'));
echo $form->input("text");
echo $form->input("Question.Test.id", array( 'value' => $test['Test']['id']  , 'type' => 'hidden') ); 
echo $form->end("Add");

将新问题与测试相关联(但确实在数据库中创建)。

$ test ['Test'] ['id']确实产生了正确的ID输出。

协助表示赞赏。

3 个答案:

答案 0 :(得分:1)

您的命名已关闭。您应该调用隐藏字段Question.test_id,因为这是应该保存值的字段。例如:

$this->Form->input('Question.test_id', array('type' => 'hidden', 'value' => $test['Test']['id']));

答案 1 :(得分:1)

您应该将hasOnehasMany关联的两个模型关联起来(如果尚未这样做),并在表questions中创建一个名为{{1的列(名为 foreignKey )。

然后问题的形式变为:

test_id

答案 2 :(得分:0)

我知道这个问题已经过时了,但对于那些像我一样来到这里寻找CakePHP 3答案的人来说,输入的关联命名约定发生了变化,table.field用于BelongsTo / HasOne关联和{{1}对于HasMany / BelongsToMany关联。

阅读the docs了解详情。