CakePHP Automagic 表单助手与关联
我有两个 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");
Nor:
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 输出。
感谢您的帮助。
I have two CakePHP models, Tests and Questions, where a Test has many questions, and a Question only has one test.
Neither this code:
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");
Nor:
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");
associates the new question with a test (but does create it in the database).
$test['Test']['id'] does produce a correct output of ID.
Assistance appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该将两个模型与
hasOne
和hasMany
关联关联(如果您尚未这样做),并在表中创建questions
名为test_id
的列(名为 foreignKey)。那么问题的形式就变成了:
You should associate (if you haven't done it yet) the two models with
hasOne
andhasMany
associations and doing so creating in the tablequestions
a column calledtest_id
(that's named foreignKey).The form of the question then becomes:
你的命名已关闭。您应该改为调用隐藏字段 Question.test_id ,因为这是应保存值的字段。例如:
Your naming is off. You should call your hidden field Question.test_id instead, since that is the field where the value should be saved. For example:
我知道这个问题已经很老了,但是对于那些像我一样来这里寻找 CakePHP 3 答案的人来说,输入的关联命名约定已经改变,用
table.field
表示 BelongsTo/HasOne 关联,>tables.field
用于 HasMany/BelongsToMany 关联。阅读文档 了解更多信息。
I know that this question is old, but for those who came here like me looking for CakePHP 3 answers, the association naming convention for inputs has changed, with
table.field
for BelongsTo/HasOne associations andtables.field
for HasMany/BelongsToMany associations.Read the docs for more info.