Laravel 4.2在数据透视表中同步多维数组 [英] Laravel 4.2 Sync multidimensional array in pivot table

查看:92
本文介绍了Laravel 4.2在数据透视表中同步多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这些是我的带有关系船功能的表.

These are my tables with relation ship functions.

问题表

id
issueName

每期都有多个问题

在Issue.php模型中

In Issue.php model

public function questions() {
        return $this->hasMany('Question','issueID','id');
    }

问题表

id
issueID
questionText
questionScore

每个问题都属于一个问题,它具有相应的分数

every question belong to an Issue, it has its corresponding score

在Question.php模型中

In Question.php model

public function issues() {
        return $this->belongsTo('Issue');
    }

使用无线电输入,我为每个Issue选择一个问题,并获取一个问题ID数组,该得分旨在保存在数据透视表中.

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.

评估表

id
totalScore

在Assessment.php模型中

in Assessment.php model

public function scores() {
            return $this->belongsToMany('Question','assessments_question_score','assessmentsID','id');
        }

在Question.php模型中

in Question.php model

public function assessments() {
            return $this->belongsToMany('Assessment');
        }

assessments_question_score表

assessments_question_score table

id
assessmentsID
questionID
score

当我尝试同步问题ID时,使用以下方式将得分评分到Assessments_question_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?

推荐答案

Assessment.php

Assessment.php

public function questions() {
   return $this->belongsToMany('Question','assessments_question_score','assessmentsID','questionID');
}

Question.php

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);

然后将ID为2、5和6的问题连接到评估中.

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');

来源: http://laravel.com/docs/4.2/eloquent#多对多 还要搜索同步".

Source: http://laravel.com/docs/4.2/eloquent#many-to-many Also search for 'sync'.

这篇关于Laravel 4.2在数据透视表中同步多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆