问题
These are my tables with relation ship functions.
issues table
id
issueName
Every Issue has multiple question
In Issue.php model
public function questions() {
return $this->hasMany('Question','issueID','id');
}
questions table
id
issueID
questionText
questionScore
every question belong to an Issue, it has its corresponding score
In Question.php model
public function issues() {
return $this->belongsTo('Issue');
}
Using radio input I am selecting a question for each Issue, and geting an array of questionID, score which is intended to save in the pivot table.
assessments table
id
totalScore
in Assessment.php model
public function scores() {
return $this->belongsToMany('Question','assessments_question_score','assessmentsID','id');
}
in Question.php model
public function assessments() {
return $this->belongsToMany('Assessment');
}
assessments_question_score table
id
assessmentsID
questionID
score
when I am trying to sync questionID, score to assessments_question_score table using
$assessments = New Assessment;
...
...
$assessments->save();
$assessments->scores()->sync($questionIDscore);
but it is not working, Is it wrong to sync multi dimentional array in sync or something else I am missing? How can I accomplish that?
回答1:
Assessment.php
public function questions() {
return $this->belongsToMany('Question','assessments_question_score','assessmentsID','questionID');
}
Question.php
public function assessments() {
return $this->belongsToMany('Assessment','assessments_question_score','questionID','assessmentsID'););
}
Then you can connect questions to an assessment like this:
$questionIds = array(2,5,6);
$assessment = new Assessment;
$assessment->save();
$assessment->questions()->sync($questionIds);
Questions with id 2, 5 and 6 are then connected to the assessment.
To get the score of the first question:
$questionScore = $assessment->questions()->first->questionScore;
To get the totalscore of all questions:
$totalScore = $assessment->questions()->sum('questionScore');
To get the average score of all questions:
$averageScore = $assessment->questions()->avg('questionScore');
Source: http://laravel.com/docs/4.2/eloquent#many-to-many Also search for 'sync'.
来源:https://stackoverflow.com/questions/29343667/laravel-4-2-sync-multidimensional-array-in-pivot-table