2012-07-24 136 views
2

我一直在試圖弄清楚如何在CakePHP中保存多級模型一段時間,但似乎無法找到解決方案。CakePHP多級模型

我有三種模式。 Survey,Question and Choice

  • 調查的hasMany 問題 - 所以問題屬於關聯調查

  • 問題的hasMany 選擇 - 所以選擇屬於關聯疑問句重刑

    • 問題通過其survey_id鍵鏈接到調查

    • 選擇,在otherhand,通過其question_id鍵鏈接到問題。 (不直接鏈接到調查雖然)

的形式通過$this->Form->create('Survey')創建。

我希望應用程序保存調查及其相應的問題,每個問題都有其相應的選擇。

問題是,只有Survey問題模型被保存。 選擇被丟棄。

我使用$this->saveAssociated($this->request->data, array('deep' => true))

我將更新我的職務,以顯示$_POST數據。

感謝,

XTN

+1

什麼版本的蛋糕您使用的通知? – jeremyharris 2012-07-24 14:32:35

回答

-1

之前保存數據,你必須確保數據應該是這種格式

在你的控制器:

$data = array('Survey' => array('id' => 1,'name' => 'test'), 
        'Question' => array(
            array('id' => 1,'question' => 'test1','survey_id' => 1, 
             'Choice' => array(
              array('id' => 1,'question_id' => 1,'choice' => 1), 
              array('id' => 2,'question_id' => 1,'choice' => 2) 
              ) 

            ), 
            array('id' => 2,'question' => 'question2','survey_id' => 1, 
            'Choice' => array(
             array('id' => 3,'question_id' => 2,'choice' => 'sd'), 
             array('id' => 4,'question_id' => 2,'choice' => 'we') 
             ) 
            ) 
           ) 
       ); 
     $this->Survey->create(); 
     $this->Survey->saveAssociated($data,array('deep'=>true)); 

調查型號:

public $hasMany = array(
    'Question' => array(
     'className' => 'Question', 
     'foreignKey' => 'survey_id', 
     'dependent' => false, 
    ) 
     ); 

問題型號:

public $belongsTo = array(
    'Survey' => array(
     'className' => 'Survey', 
     'foreignKey' => 'survey_id', 
    ) 
); 
public $hasMany = array(
    'Choice' => array(
     'className' => 'Choice', 
     'foreignKey' => 'question_id', 
     'dependent' => false, 
    ) 
); 

選擇模型:

public $belongsTo = array(
    'Question' => array(
     'className' => 'Question', 
     'foreignKey' => 'question_id', 
    ) 
); 

我認爲它會工作,如果發現有任何問題,請

+0

這就是我要找的。奇蹟般有效。謝謝! – czt 2012-07-26 14:14:59

-1

你的模型應該是這樣的:

Survey Model: Survey.php

class Survey extends AppModel { 
    public $name = 'Survey'; 
    public $hasMany = array('Questions' => array(
              'className' => 'Question', 
              'foreignKey' => 'survey_id' 
               ) 
          ); 
} 

Question Model: Question.php

class Question extends AppModel{ 
public $name = 'Question'; 
public $belongsTo = array(
         'Survey' => array('className' => 'Survey', 'foreignKey' => 'survey_id'), 
         'Answer' => array('className' => 'Choice', 'foreignKey' => 'answer_id')); 
public $hasMany = array('Choices' => array('className' => 'Choice', 
              'foreignKey' => 'question_id')); 
} 

Choice Model: Choice.php

class Choice extends AppModel 
{ 
public $name = 'Choice'; 
public $belongsTo = array('Question' => array('className' => 'Question', 
               'foreignKey' => 'question_id')); 
} 

請問是否它不適合你。

+0

這工作!謝謝 – czt 2012-07-26 14:15:23