2016-06-21 3 views
1

두 개의 테이블 (기사 및 내용)에 데이터를 게시하고 싶습니다.CakePHP 3의 두 개의 다른 테이블에 데이터 저장

내용은 제품 (하나의 제에 대해 여러 내용을) 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' 
    ]); 
} 

가 지금은 테이블의 모든 내용을 게시하고 또한 하나 개의 기사를 만들려면 내에서 작성된 것입니다.

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

ContentsController.php 나는 associated를 사용하여 그것을 할 시도했지만 작동하지 않았다.

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

"_doesn't work_"은 (는) 적절한 문제 설명이 아닙니다! 문제가 CakePHP 내부를 아는 사람들에게 명백 할지라도, _ 정확한 _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 발생하는 경우와 _ _ _ _ _ 가능한 _ 구체적인 _으로 _하십시오. 작업중인 데이터 (포스트 데이터), 문제를 재현하는 데 필요한 코드 (newEntity() 호출뿐만 아니라 모든 엔티티/코드 저장), 디버깅 시도 ("해결 방법"시도가 아닌)) 및 가능한 오류 (유효성 검사 오류, 예외 사항 등)가 있습니다. 종종 이러한 정보를 수집 할 때 문제가 해결됩니다. – ndm

답변

2

Try and Error는 저를 해결책 + 독서 다시 읽었습니다 ... 그리고 또 다시. 기사

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