将数据保存到 CakePHP 3 中的两个不同表

Save data to two different tables in CakePHP 3

我想post数据到两个表(文章和目录)。

Contents belongsTo Articles(一篇文章有​​多个内容)这是写在我的ContentsTable.php

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

    $this->table('contents');
    $this->displayField('id');
    $this->primaryKey('id');

    $this->addBehavior('Timestamp');

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

现在我想 post table 中的所有内容并创建一篇文章。

ContentsController.php

public function add()
{
    $content = $this->Contents->newEntity();
    $id = $this->Auth->user('id');

    if ($this->request->is('post')) {
        $contents = $this->Contents->newEntities($this->request->data());

        foreach ($contents as $content) {
            $content->article_id = $id;
            $this->Contents->save($content);
        }

    }

    $this->set(compact('content'));
    $this->set('_serialize', ['content']);
}

我尝试使用 associated 来做到这一点,但没有成功。

$content = $this->Contents->newEntity($this->request->data, [
            'associated' => ['Articles']
        ]);

尝试和错误让我找到了解决方案 + 再次阅读文档……又一遍。

文章控制器

public function add()
    {
        $article = $this->Articles->newEntity();
        if ($this->request->is('post')) {
            $article = $this->Articles->patchEntity($article, $this->request->data, [
                'associated' => [
                    'Contents'
                ]
            ]);
            // Added this line
            $article->user_id = $this->Auth->user('id');

            if ($this->Articles->save($article, array('deep' => true))) {               

            }
            $this->Flash->error(__('Unable to add your article.'));
        }
        $this->set('article', $article);

    }

在文章中测试add.ctp

echo $this->Form->hidden('contents.0.article_id');
                echo $this->Form->hidden('contents.0.type', ['value' => '1']);
                echo $this->Form->hidden('contents.0.position', ['value' => '3']);
                echo $this->Form->hidden('contents.0.text', ['value' => 'test']);

                echo $this->Form->hidden('contents.1.article_id');
                echo $this->Form->hidden('contents.1.type', ['value' => '7']);
                echo $this->Form->hidden('contents.1.position', ['value' => '7']);
                echo $this->Form->hidden('contents.1.text', ['value' => 'test7']);

并将此添加到我的 ArticlesTable.php

$this->hasMany('Contents');