这是我的模特:
class Question extends AppModel {
public $hasMany = array(
'CaseQuestions' => array('className'=>'Question', 'foreignKey'=>'parent_id')
);
public $hasOne = array(
'CaseStudy' => array('className'=>'Question', 'foreignKey'=>'parent_id')
);
这是我的控制器中的动作:
public function admin_delete_case_question($question_id) {
$this->Question->Behaviors->load('Containable');
$this->Question->contain( array('CaseStudy'));
$question = $this->Question->findById($question_id );
debug($question);
exit;
上面的调试返回如下内容:
array(
'Question' => array(
'id' => '78',
'nickname' => '',
'content' => 'sdgsdfgs',
'type' => 'CQ',
'option1' => 'sdfgsdfg',
'option2' => '',
'option3' => '',
'option4' => '',
'time' => '-1',
'difficulty' => '0.0000',
'slope' => '0.0000',
'chance' => '0',
'experiment' => false,
'created' => '2013-05-02 16:30:29',
'modified' => '2013-05-02 16:30:29',
'status' => null,
'perm_id' => '76',
'notes' => null,
'is_deleted' => false,
'answer_id' => '0',
'parent_id' => '77',
'order' => null
),
'CaseStudy' => array(
'id' => null,
'nickname' => null,
'content' => null,
'type' => null,
'option1' => null,
'option2' => null,
'option3' => null,
'option4' => null,
'time' => null,
'difficulty' => null,
'slope' => null,
'chance' => null,
'experiment' => null,
'created' => null,
'modified' => null,
'status' => null,
'perm_id' => null,
'notes' => null,
'is_deleted' => null,
'answer_id' => null,
'parent_id' => null,
'order' => null
)
)
我不明白为什么CaseStudy数组全为NULL,因为当我在DB中查看该记录(id 77)时,所有数据都是正确的。我做错了什么?
答案 0 :(得分:3)
在你的例子中......问题有一个CaseStudy;这意味着问题是父母。
根据您的数据,您的问题有一个parent_id,所以我假设您实际上意味着CaseStudy是父,而Question是孩子。看起来您的关联实际上是倒退的(通常父节点不会有parent_id)。
使用belongsTo替换你的hasOne关联:
public $belongsTo = array(
'CaseStudy' => array('className'=>'Question', 'foreignKey'=>'parent_id')
);
这将确保CaseStudy是父级,而问题是孩子。
按照目前设置的方式,CakePHP正在尝试寻找一个父类与您的Question.id相等的CaseStudy;因为你的数据库中没有任何类似的数据,CakePHP找不到任何内容并返回空值。 实际上,CaseStudy实际上是父,而Question的parent_id等于CaseStudy.id
答案 1 :(得分:2)
请改为尝试:
//Question model
public $actsAs = array('Containable'); //personally, I put this in my AppModel
//QuestionsController
$question = $this->Question->find('first', array(
'conditions' => array(
'id' => $question_id
),
'contain' => array(
'CaseStudy'
)
));