在Yii中,我有一个视图,显示一个问题,提出相关答案的问题,以及每个答案相关的评论。
我的问题是:如何从控制器/模型中检索模型的关系的当前id,而不导航到特定于该关系的视图?
更多详情:
关系的foreach循环是每个设置,数据正确显示没有问题。
有一个视图有很多嵌套的'renderPartial'视图,但是一个问题和所有相关的答案/评论都显示在同一页面上。
每个答案都有一个数据库字段question_id,它是问题PK的FK。我用来设置要保存的正确模型对象的代码和正确的当前question_id是: QuestionController.php中的函数:
/**
* creates answer model and if answer is being submitted via post, saves the answer data
* @protected
* @return object answer object being saved
*/
protected function createAnswer($question)
{
$answer = new Answer();
if(isset($_POST['Answer']))
{
$answer->attributes = $_POST['Answer'];
if($question->addAnswer($answer))
{
Yii::app()->user->setFlash('answerSubmitted', "Thank you for your answer!");
$this->refresh();
}
}
return $answer;
}
在QuestionController.ActionView:
中调用此函数 /**
* Displays a particular model.
*/
public function actionView()
{
//load question model
$question = $this->loadModel();
//load associated answers for question
$answer = $this->createAnswer($question);
//load associated comments for answers
$comments = $this->createComment($question->answer);
$this->render('view',array(
'model'=>$question,
'answer'=>$answer,
'comments'=>$comments,
));
}
这很好用,createAnswer函数在Question.php模型中调用以下函数:
/**
* Adds an answer to this question
* @param model answer the answer model
* @return model saved answer with the current question's id
*/
public function addAnswer($answer)
{
$answer->question_id = $this->id;
$answer->status = param('answerStatus');
return $answer->save();
}
上面的代码设置当前问题的ID,效果很好。
我遇到的问题是为评论的答案设置正确的answer_id。我试图在QuestionController中使用以下代码:
/**
* @protected
* @return object comment object being saved
* Saves comment for this particular answer
*/
protected function createComment($answer)
{
$comment = new AnswerComment;
if(isset($_POST['AnswerComment']))
{
$comment->attributes = $_POST['AnswerComment'];
if($answer->addComment($comment))
{
//Yii::app()->user->setFlash('commentSubmitted', $answer->answer->id . 't');
Yii::app()->user->setFlash('commentSubmitted', "Your comment has been added.");
$this->refresh();
}
}
return $comment;
}
并在Answer模型中调用该函数:
/**
* Adds a comment to this answer
* @param model answer the answer model
* @return model saved answer with the current question's id
*/
public function addComment($comment)
{
$comment->answer_id =$this->id;
$comment->status = param('answerCommentStatus');
return $comment->save();
}
然而,这不起作用。 $this->id
显然没有设置。我相信这可能是因为它是主模型的关系而不是主模型本身。如何在不转到特定于该答案的视图(即/ answer / view / 1等)的情况下检索当前答案的ID。
(作为一个例子,想一想StackOverflow如何让你在不离开问题的页面的情况下评论不同的答案)
谢谢!