2016-06-21 39 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'); 
相關問題