CakePHP 3.x:将一个输入保存到多个表中

Posted

技术标签:

【中文标题】CakePHP 3.x:将一个输入保存到多个表中【英文标题】:CakePHP 3.x: saving one input into multiple tables 【发布时间】:2016-01-15 11:11:31 【问题描述】:

对不起,我不得不再问一次,但我正在努力将一个输入保存到两个表中。

我的第一张桌子:

deceases
 - id
 - other records
 - funeral_id
 - cemetery_id

我的第二张桌子:

funerals
 - id
 - other records
 - cemetery_id

我的第三张桌子:

cemeteries
 - id
 - other records

协会:

One decease belongs to a funeral. A funeral has many deceases.
One decease belongs to a cemetery. A cemetery has many deceases.
One funeral belongs to a cemetery. A cemetery has many funerals.

在 DeceasesController 的添加操作中,我想将 cemetery_id 保存到 deceasesfunerals 中,只有一个输入。

死亡和葬礼的其他输入保存得很好,但我不明白Cakephp的文档如何保存cemetery_id

DeceasesController:

public function add() 

        $decease = $this->Deceases->newEntity();
        if ($this->request->is('post')) 
            $decease = $this->Deceases->patchEntity($decease, $this->request->data, [
                'associated' => [
                    'Funerals', 
                    'Cemeteries' 
                ]
            ]);
            if ($this->Deceases->save($decease)) 
                $this->Flash->success(__('Saving successfully.'));
                return $this->redirect(['action' => 'index']);
             else 
                $this->Flash->error(__('Saving wasn´t successful. Try again.'));
            
        

        $cemeteries = $this->Deceases->Cemeteries->find('list', ['limit' => 300]);
        $funerals = $this->Deceases->Funerals->find('list', ['limit' => 200]);
        $this->set(compact('decease', 'cemeteries', 'funerals'));
        $this->set('_serialize', ['decease']);
    

add.ctp 的片段:

echo $this->Form->input('funeral.cemetery_id', ['options' => $cemeteries, 'label' => 'cemetery']);

希望您能够理解我的问题。英语不是我的第一语言。

提前致谢。

【问题讨论】:

【参考方案1】:

希望我能理解你的问题:

patchEntity 之后和保存之前在您的控制器中,您可以这样做

$decease->cemetery_id = $decease->funeral->cemetery_id;

因此,死亡和葬礼都将设置相同的值

【讨论】:

完美。非常感谢你。

以上是关于CakePHP 3.x:将一个输入保存到多个表中的主要内容,如果未能解决你的问题,请参考以下文章

将数据保存到 2 个表中 cakephp 3

CakePHP 3.x - 保存这些表的关联数据和表单输入

Cakephp 3.x 保存 hasmany 关联

CakePHP:将数据保存到 3 个不同的模型

CakePHP 3.0 保存我的关联数据

Cakephp 多个输入字段