2016-06-21 82 views
1

我想将数据发布到两个表(文章和内容)。将数据保存到CakePHP中的两个不同表3

内容属于关联文章(一多条内容),这是写在我的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'] 
     ]); 
+0

“_doesn't work_”不是一个合适的问题描述!即使问题对于了解CakePHP内部的人来说可能是显而易见的,请始终尽可能具体说明_exactly_发生了什么,以及您期望发生什么。显示您正在使用的数据(发布数据),重现问题所需的代码(所有实体/保存代码,不仅仅是newEntity()调用),您的调试尝试(而不仅仅是“解决方法”尝试)和可能的错误(验证错误,异常等)。收集此类信息时,问题通常会自行解决。 – ndm

回答

2

尝试和错误将我引向解决方案+再次阅读文档...并再次。在文章

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

文章控制器

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,并将此我ArticlesTable.php

$this->hasMany('Contents'); 
相关问题