在将Fisica实体保存到数据库时,曾试图将数据保存到其他表中,因为我是Cakephp的新手,所以现在看来似乎是不可能的,已经看过多个帖子,视频,文档,而且似乎都不起作用。请有人帮助我找出问题所在。
我在实体之间的关系中发现了一个巨大的错误,现在这样工作: Fisica属于Pessoa
FisicasTable.php的关联
$this->belongsTo('Pessoa')
->setForeignKey('id_pessoa')
->setJoinType('INNER')
->setClassName('Pessoas');
Fisicas Controller
$fisica = $this->Fisicas->newEntity();
if ($this->request->is('post')) {
$fisica = $this->Fisicas->patchEntity($fisica, $this->request->getData(),['associated' => 'Pessoa']);
if ($this->Fisicas->save($fisica))...
Fisica add.ctp
<legend><?= __('Add Fisica') ?></legend>
<?php
echo $this->Form->control('nr_cpf');
echo $this->Form->control('dt_nascimento');
?>
<legend><?= __('Add Pessoa') ?></legend>
<?php
echo $this->Form->control('pessoa.vr_nome');
echo $this->Form->control('pessoa.nr_telefone');
echo $this->Form->control('pessoa.vr_email');
?>
我收到以下错误: error
当我向Fisica add.ctp提交新的寄存器时,我希望这段代码可以插入到两个表中。
答案 0 :(得分:0)
我发现我在结合主键命名模式来命名数据库中的表时遇到问题。只需将表的名称更新为“ Fisicas”和“ Pessoas”,并将其主键和外键更改为fisica_id和pessoa_id,然后使用bake生成所有代码(例如,将所有pessoas蛋糕烘焙)即可解决问题(并生成关联)自动)。
答案 1 :(得分:-2)
您必须获取用于存储数据的所有表,请参阅文档https://book.cakephp.org/3.0/en/orm/saving-data.html#saving-with-associations 代码示例是
// Prior to 3.6.0
$articlesTable = TableRegistry::get('Articles');
$articlesTable = TableRegistry::getTableLocator()->get('Articles');
$author = $articlesTable->Authors->findByUserName('mark')->first();
$article = $articlesTable->newEntity();
$article->title = 'An article by mark';
$article->author = $author;
if ($articlesTable->save($article)) {
// The foreign key value was set automatically.
echo $article->author_id;
}