簡體   English   中英

CakePHP:將多個條目從另一個控制器保存到模型

[英]CakePHP: Saving multiple entries to a model from a different controller

我有一個具有“學校”表和“學生”表的數據庫。 顯然,一所學校有很多學生,這在DB中有代表。

在CakePHP中進行“烘焙”之后,我的添加函數都可以使用其默認格式。 我可以創造學生,也可以創造學校。 但是,我希望每當創建學校時都能創建兩個學生。 因此,我在學校的“ 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() ?>

但是我找不到解決方案可以修改SchoolsController.php文件中學校的“添加”功能來保存兩個學生。 我該怎么做?

編輯:這是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
                )
        )
)

您提供的發布數據似乎正確,因此您可以像這樣修改保存功能:

$school = $this->Schools->newEntity($this->request->data, ["associated" => ["Students"]]);
$this->Schools->save($school);

進一步閱讀: https : //book.cakephp.org/3.0/en/orm/saving-data.html#saving-hasmany-associations

在您的添加函數中:

if $this->request->is('post') {

    $students = $this->Students->newEntities($this->request->data()['students']);

    foreach ($students as $student) {
        $this->Students->save($student);
    }
}

來源: https : //book.cakephp.org/3.0/en/orm/saving-data.html#converting-multiple-records

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM