我有两个表,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']);
    }

最佳答案

我认为这应该工作:

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内容,并用input('first_name')和input('last_name')替换您的input('shashi_detail.first_name')和input('shashi_detail.last_name')。

09-04 21:15