CakePHP 3.x-保存关联数据

时间:2019-05-16 08:33:25

标签: cakephp cakephp-3.x cakephp-3.6

我正在尝试使用连接表来修补实体,但无法获取它来保存关联的记录,并且我认为后端代码正确,但是不确定前端代码的外观。

这是场景,我有三个表

分类帐表

id int
title string

部落表

id int
name string

LedgersTribes表

id int
ledger_id int
tribe_id int

这是我的后端代码

public function ledgerSave($id = null)
{
    $this->loadModel('Ledgers');

    $ledger = $this->Ledgers->get($id, [
        'contain' => ['LedgersTribes']
    ]);

    if ($this->request->is(['patch', 'post', 'put'])) {
         $ledger = $this->Ledgers->patchEntity($ledger, $this->request->getData(), [
             'associated' => ['LedgersTribes']
         ]);
         if ($this->Ledgers->save($ledger)) {
             $this->Flash->success(__('The ledger has been saved.'));

             return $this->redirect($this->referer());
         }
         $this->Flash->error(__('The ledger could not be saved. Please, try again.'));
    }
    $this->set(compact('ledger'));
}

这是相关的前端代码

<?= $this->Form->control('tribe_id[]', ['type' => 'checkbox', 'label' => false, 'class' => 'minimal', 'value' => $tribe->id]) ?>

我的问题是,tribe_id的字段名称应该是什么,这个想法是,我有一个复选框列表,用户选中了几个框,然后将这些tribe_id插入到带有ledger_id的LedgersTribes表中。 / p>

关于如何做到这一点的任何想法?


编辑:这是表单的屏幕截图

enter image description here


我查看了以下链接,但没有一个回答我的问题...

CakePHP 3: Save Associated Model Fail

Save associated in cakephp 3 not working

How to save associated joinData in cakephp 3.x

CakePHP 3 cannot save associated model

Cakephp 3 - Save associated belongsToMany (joinTable)

2 个答案:

答案 0 :(得分:0)

这应该做:

echo $this->Form->control('tribes._ids[]', [        
    'type' => 'checkbox', 
    'label' => false, 
    'class' => 'minimal', 
    'value' => $tribe->id]
]);

此处描述:https://book.cakephp.org/3.0/en/views/helpers/form.html#creating-inputs-for-associated-data

答案 1 :(得分:-1)

我认为您必须在要保存数据的地方获取表(例如:TableRegistry :: getTableLocator()-> get(''))。然后从中创建实体并保存数据,希望它可以工作。