2011-04-18 31 views
1

如何添加項目並將其插入到2個表格中?CakePHP - 將項目添加到2個模型

所以我有一個'Type'表和'SpecificType'表。

類型具有字段'id'和一些其他常見字段。
SpecificType具有字段'id','type_id'和一些其他不常見的字段。

當我去/ specific_types /添加和我提交,理想情況下,我想先將其添加到'類型',然後將其添加到'SpecificType'。

這就是我現在擁有的。

在SpecificType型號

var $belongsTo = array(
    'Type' => array(
     'className' => 'Type', 
     'foreignKey' => 'type_id', 
     'conditions' => '', 
     'fields' => '', 
     'order' => '' 
    ) 
); 

在SpecificType控制器

var $uses = ('Type', 'SpecificType'); 

function add() { 
    if (!empty($this->data)) { 
     $this->Type->create(); 
     if ($this->Type->save($this->data)) { 
      $this->SpecificType->create(); 
      if ($this->SpecificType->save($this->data)) { 
       $this->Session->setFlash(__('The SpecificType has been saved', true)); 
       $this->redirect(array('action' => 'index')); 
      } else { 
       $this->Session->setFlash(__('The SpecificType could not be saved. Please, try again.', true)); 
      } 
     } else { 
      $this->Session->setFlash(__('The Type could not be saved. Please, try again.', true)); 
     } 
    } 
} 

在SpecificType add.ctp

echo $form->input('Type.data1'); 
echo $form->input('title'); 

所以,現在,這樣可以節省Type.data1但標題是不是得到保存。 我錯過了什麼?

感謝,
三通

附加信息: 當我打開MeioUpload第二屆模式不僅節省。

回答

0

只需將數據複製到數據數組中的SpecificType索引並使用saveAll()即可。模型是相關的,所以Cake會通過type_id自動鏈接它們。我們正在處理Type別名,因此請確保您的Type型號中也有var $hasMany = array('SpecificType');

function add() { 
    if (!empty($this->data)) { 
     $this->Type->create(); 
     $this->data['SpecificType'] = $this->data; 
     if ($this->Type->saveAll($this->data)) { 
      $this->Session->setFlash(__('The SpecificType has been saved', true)); 
      $this->redirect(array('action' => 'index')); 
     } else { 
      $this->Session->setFlash(__('The SpecificType could not be saved. Please, try again.', true)); 
     } 
    } else { 
     $this->Session->setFlash(__('The Type could not be saved. Please, try again.', true)); 
    } 
} 
+0

感謝泰勒。除了插入的數據似乎有缺陷之外,這幾乎是工作。例如'我的標題'變成'2y標題'。爲什麼第一個字符是隨機替換的? – teepusink 2011-04-19 04:14:09

1

確保你的觀點是建立創建SpecificType形式:

<?php echo $this->Form->create('SpecificType', array('action' => 'add')); ?> 
<?php echo $this->Form->input('data1'); ?> 
<?php echo $this->Form->input('title'); ?> 
<?php echo $this->Form->end(); ?> 

這將會把所有的表單數據爲:$this->data['SpecificType']

權代碼之前:

$this->Type->create(); 

您需要執行此操作:

$this->data['Type'] = $this->date['SpecificType']; 

然後處理保存。只要特定類型控制器的視圖設置正確,表單中的所有數據都將存儲在$this->data['SpecificType']中。如果您pr($this->data)並且有數據需要保存在$this->data['SpecificType']之外,請查看並修復該視圖。

便箋:您的設計聽起來非常粗略。你永遠不需要將數據保存在兩個位置。我會建議重新審視你的應用程序的設計。如果您需要將相同的數據保存到兩個表格中,則會出現根本性錯誤。

0

該代碼似乎很好,使用saveAll而不是保存