Isengo
Isengo

Reputation: 2073

Save data to two different tables in CakePHP 3

I want to post data to two Tables (Articles and Contents).

Contents belongsTo Articles (multiple Contents for one Article) and this is written in my 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'
    ]);
}

Now I want to post all the Contents in the table and also create one article.

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

I tried to do it by using associated, but it didn't work.

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

Upvotes: 1

Views: 2545

Answers (1)

Isengo
Isengo

Reputation: 2073

Try and Error leaded me to the solution + Reading the Docs again... and again.

Articles Controller

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

    }

Test add.ctp in Articles

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

And added this to my ArticlesTable.php

$this->hasMany('Contents');

Upvotes: 2

Related Questions