简体   繁体   中英

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.

After 'baking' in CakePHP, my add functions were all fine with their default forms. 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:

<?= $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. How would I do this?

EDIT: Here is the POST data:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM