[英]CakePHP: Saving multiple entries to a model from a different controller
I have a database that has a 'Schools' table and a 'Students' table. 我有一个具有“学校”表和“学生”表的数据库。 Obviously, a school has many students, and this is represented in the DB. 显然,一所学校有很多学生,这在DB中有代表。
After 'baking' in CakePHP, my add functions were all fine with their default forms. 在CakePHP中进行“烘焙”之后,我的添加函数都可以使用其默认格式。 I could create students, and I could create schools. 我可以创造学生,也可以创造学校。 However I would like to be able to create two students whenever I create a school. 但是,我希望每当创建学校时都能创建两个学生。 So I set up my form like this in the school's 'add.ctp' file: 因此,我在学校的“ add.ctp”文件中设置了这样的表单:
<?= $this->Form->create('school') ?>
<fieldset>
<legend><?= __('Add School') ?></legend>
<?php
// create the school
echo $this->Form->input('school_name');
echo $this->Form->input('school_description');
echo $this->Form->input('student.0.name');
echo $this->Form->input('student.0.description');
echo $this->Form->input('student.1.name');
echo $this->Form->input('student.1.description');
?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
However no solution I can find is able to work for modifying the school's 'add' function in the SchoolsController.php file to be able to save the two students. 但是我找不到解决方案可以修改SchoolsController.php文件中学校的“添加”功能来保存两个学生。 How would I do this? 我该怎么做?
EDIT: Here is the POST data: 编辑:这是POST数据:
Array
(
[school_name] => Harvard
[school_description] => A University
[students] => Array
(
[0] => Array
(
[name] => Bob Brown
[description] => Likes frogs
)
[1] => Array
(
[name] => James Jones
[description] => Plays trumpet
)
[2] => Array
(
[name] => Sarah Simmer
[description] => Enjoys movies
)
)
)
The post data you provided seems correct, so you can modify your save function like this: 您提供的发布数据似乎正确,因此您可以像这样修改保存功能:
$school = $this->Schools->newEntity($this->request->data, ["associated" => ["Students"]]);
$this->Schools->save($school);
Further reading: https://book.cakephp.org/3.0/en/orm/saving-data.html#saving-hasmany-associations 进一步阅读: https : //book.cakephp.org/3.0/en/orm/saving-data.html#saving-hasmany-associations
In your add function: 在您的添加函数中:
if $this->request->is('post') {
$students = $this->Students->newEntities($this->request->data()['students']);
foreach ($students as $student) {
$this->Students->save($student);
}
}
source: https://book.cakephp.org/3.0/en/orm/saving-data.html#converting-multiple-records 来源: https : //book.cakephp.org/3.0/en/orm/saving-data.html#converting-multiple-records
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.