2011-04-18 58 views
2

我有兩個表,questionstags,它們有一個HABTM關係。添加問題時,我希望能夠爲問題指定一個標籤(這只是第一個標籤,稍後可以添加更多標籤)。標籤從桌子上拉出來。如何配置我的應用程序,以便在添加問題並指定標記時,連接將反映在連接表(questions_tags)中?CakePHP HABTM表單提交

這裏是我的問題添加動作代碼:

function add() { 
    $tags = $this->Question->Tag->find('all'); 
    $this->set('tags',$tags); 

    if (!empty($this->data)) { 
     $this->Question->create(); 
     if ($this->Question->save($this->data)) { 
      $this->Session->setFlash(__('The question has been saved', true)); 
      $this->redirect(array('action' => 'index')); 
     } else { 
      $this->Session->setFlash(__('The question could not be saved. Please, try again.', true)); 
     } 
    } 
    $users = $this->Question->User->find('list'); 
    $tags = $this->Question->Tag->find('list'); 
    $this->set(compact('users', 'tags')); 
} 

,這裏是我的問題添加視圖代碼:

<?php 
    echo $this->Form->create('Question'); 
    echo $this->Form->input('user_id',array('type' => 'hidden', 'value' => $this->Session->read('Auth.User.id'))); 
    echo $this->Form->input('title'); 
    echo $this->Form->input('details',array('type' => 'textarea')); 
    echo $this->Form->input('tag_id'); 
    echo $this->Form->end(__('Submit', true)); 
?> 
+0

您的代碼看起來像是設置了一個問題屬於標記設置。看看這個食譜條目:http://book.cakephp.org/view/1034/Saving-Related-Model-Data-HABTM – JohnP 2011-04-18 07:28:57

回答

3

首先確保你的模型樹立正確的方式鏈接。事實上,用戶最初只是爲您的問題添加一個標籤並不會改變您在Question模型和標籤模型之間應該具有HABTM關係的事實(因爲您希望稍後可能添加更多標籤)。

如果您$this->data陣列是根據以下模式構建:

$this->data = array(
    'Question' => array(
    'name' => 'Trick question' 
), 
    'Tag' => array(
    'Tag' => array(1,2,3) 
) 
); 

然後,$this->Question->save()將保存問題的數據以及相關的標籤數據(在這種情況下,問題「腦筋急轉彎」與標籤id 1,2和3)。可能需要退一步,爲這兩個模型(再次)烘焙您的模型,視圖和控制器,然後查看Cake所做的一切。如果我是正確的,你只需要一個$this->Form->input('Tag')在你的表單的某個地方(如果沒有自動填寫正確的數據,你想填寫options參數,結果爲$this->Question->Tag->find('list'))。

0

,如果你有一個標籤的問題,它不是HABTM。它必須是一對一或一對多的關係。

在你的問題的模型,你可以定義屬性屬於關聯:

class Question extends AppModel { 
    var $name = 'Question';   
    var $belongsTo = array(
     'Tag' => array(
      'className' => 'Tag', 
      'foreignKey' => 'tag_id'    
     ) 
    );  
} 

這樣的事情。

這裏是描述如何設置HABTM

HABTM

+0

檢查我的編輯。用戶在提出問題時將選擇一個標籤,因爲這只是一個起始標籤,用戶以後可以添加更多標籤。 – 585connor 2011-04-18 07:43:00