2012-07-24 141 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