cakephp3.x同时在两个表中进行inseritng数据

时间:2017-10-12 12:42:05

标签: php mysql cakephp cakephp-3.0

我有两个表,shashisshashi_details。我想要做的就是一次在两个表中插入数据,所以当我插入数据时,它只会进入shashis表,而不会进入另一个表。所以请帮帮我。

这是我的ShashisTable.php

    class ShashisTable extends Table
{

    public function initialize(array $config)
    {
        parent::initialize($config);

        $this->setTable('shashis');
        $this->setDisplayField('name');
        //$this->setDisplayField('id');
        $this->setPrimaryKey('id');

        $this->addBehavior('Timestamp');

        $this->hasOne('ShashiDetails', [
            'foreignKey' => 'shashi_id'
        ]);
    }

这是我的ShashiDetails.php

     public function initialize(array $config)
    {
        parent::initialize($config);

        $this->setTable('shashi_details');
        $this->setDisplayField('id');
        $this->setPrimaryKey('id');

        $this->addBehavior('Timestamp');

        $this->belongsTo('Shashis', [
            'foreignKey' => 'shashi_id',
            'joinType' => 'INNER'
        ]);
    }

这是Shashis模板的add.ctp

    <?= $this->Form->create($shashi) ?>

    <fieldset>
        <legend><?= __('Add Shashi') ?></legend>
        <?php
            echo $this->Form->input('name');
            echo $this->Form->input('email');
        ?>
    </fieldset>

    <fieldset>
        <legend><?= __('Add details') ?></legend>
        <?php
            echo $this->Form->input('shashi_detail.first_name');
            echo $this->Form->input('shashi_detail.last_name');
        ?>
    </fieldset>

    <?= $this->Form->button(__('Submit')) ?>

这是ShashisController.php

 public function add()
    {
        $shashi = $this->Shashis->newEntity();
        if ($this->request->is('post')) 
        {
            $shashi = $this->Shashis->patchEntity($shashi, $this->request->getData(), [
                'associated' => ['ShashiDetails']
                ]);

            if ($this->Shashis->save($shashi)) 
            {
                $this->Flash->success(__('The shashi has been saved.'));

                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error(__('The shashi could not be saved. Please, try again.'));
        }
        $this->set(compact('shashi'));
        $this->set('_serialize', ['shashi']);
    }

1 个答案:

答案 0 :(得分:0)

我认为这应该有效:

if ($this->Shashis->save($shashi)) 
{
    $shashi_details = $this->Shashis->ShashisDetails->newEntity();
    $shashi_details = $this->Shashis->ShashisDetails->patchEntity($shashi_details, $this->request->getData());
    if ($this->Shashis->ShashisDetails->save($shashi_details))
    {
        $this->Flash->success(__('The shashi has been saved.'));
        return $this->redirect(['action' => 'index']);
    }
}

如果没有,请检查您的POST内容并替换输入('shashi_detail.first_name')和输入('shashi_detail.last_name')输入('first_name')和输入('last_name')。