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

时间:2016-06-21 13:59:02

标签: php cakephp cakephp-3.x

我想将数据发布到两个表(文章和内容)。

目录belongsTo文章(一篇文章的多个内容),这是写在我的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'
    ]);
}

现在我想在表格中发布所有内容,并创建一篇文章。

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']
        ]);

1 个答案:

答案 0 :(得分:2)

尝试和错误让我找到解决方案+再次阅读文档......再次。

文章控制器

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');