如何计算列

时间:2019-06-22 12:51:24

标签: laravel

我有十二个学生分数整数输入字段,一个学生最多可以尝试10个考试,最少可以进行7个考试,我的问题是,当一个学生尝试7个考试时,我只需要平均7个科目,谁可以帮助我执行此操作。

我是根据视图进行计算

    <td>{{round(((
           $formone->civ +
           $formone->hist +
           $formone->geo +
           $formone->kisw +
           $formone->engl +
           $formone->phy +
           $formone->chem +
           $formone->bio +
           $formone->ict +
           $formone->bm +
           $formone->comm +
           $formone->bk
         )/12),3)}} 
    </td>
    <td>{{ $formone->civ +
           $formone->hist +
           $formone->geo +
           $formone->kisw +
           $formone->engl +
           $formone->phy +
           $formone->chem +
           $formone->bio +
           $formone->ict +
           $formone->bm +
           $formone->comm +
           $formone->bk
        }} 
    </td>

1 个答案:

答案 0 :(得分:1)

您可以在模型上放置一个accessor来计算average

/* ACCESSORS */
public function getAverageAttribute()
{
    $subjects = ['civ', 'hist', 'geo', 'kisw', 'engl', 'phy', 'chem', 'bio', 'ict', 'bm', 'comm', 'bk',];
    $subjectCount = 0;
    $totalMarks = 0;

    foreach ($subjects as $subject) {
        // ASSUMPTION: Marks are null if the student did not attempt it.
        if ($this->attributes[$subject]) {
            $totalMarks += $this->attributes[$subject];
            $subjectCount++;
        }
    }
    return round($totalMarks / $subjectCount, 3);
}

将其用作您的视图

<td> {{$formone->average}} </td>