CakePHP保存三模型关系关联
我有以下输出,需要将其插入数据库中:
Array
(
[Test] => Array
(
)
[Question] => Array
(
[0] => Array
(
[category_id] => 3
[answer_style_id] => 2
[Answer] => Array
(
[0] => Array
(
[capital_category_id] => 14
[correct] => 1
)
...
...
简而言之,每个测试都有许多问题,每个问题都有许多答案,每个关联的模型都有一个需要由 Cake 设置的外键(每个问题都有一个 test_id,每个答案都有一个 Question_id)。
问题是,当我 $this->Test->saveAll($data);
时,仅保存测试和问题,而不保存答案。
如何保存所有数据,并让 Cake 自动为每个关联模型设置外键?
谢谢你!
I have the following output which I need to be inserted in the database:
Array
(
[Test] => Array
(
)
[Question] => Array
(
[0] => Array
(
[category_id] => 3
[answer_style_id] => 2
[Answer] => Array
(
[0] => Array
(
[capital_category_id] => 14
[correct] => 1
)
...
...
Briefly, each Test hasMany Questions, and each Question hasMany Answer, with each associated model having a foreign key which need to be set by Cake (each Question has a test_id, and each Answer has a question_id).
The problem is that when I $this->Test->saveAll($data);
, only the Test and the Questions get saved, not the answers.
How can I save all data, with Cake automagically setting the foreign key for each associated model?
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不确定,但我认为不可能保存第三层关系。
来自 Cakephp:
您必须检索第三级数据并将其与它们分开保存。
I'm not sure but I think it's impossible to save third level relation.
from Cakephp:
you'll have to retrieve third level data and save it apart from them.
是的,从 CakePHP 2.1 开始,您可以通过这种方式保存深层模型树
参考此处> http://book.cakephp.org/2.0/en/appendices/new-features-in-cakephp-2-1.html#model-saveall-model-save Associated-model-validate Associate
Yes, you can save deep model trees since CakePHP 2.1 this way
Reference here > http://book.cakephp.org/2.0/en/appendices/new-features-in-cakephp-2-1.html#model-saveall-model-saveassociated-model-validateassociated
我有三个模型 A、B 和 C
A 有很多 B
B hasMany C
$A->saveAll() 将保存模型 A & B 但不是 C
这是我使用的一个解决方法:
在模型 B 中重写 afterSave 像这样
I have three models A, B and C
A hasMany B
B hasMany C
$A->saveAll() will save model A & B but not C
Here is a playaround I use:
in model B override afterSave like this