雄辩,如何获得新字段中的字段总和

问题描述 投票:0回答:1

我有一个数据库表students,每个主题的所有科目最终成绩是一个非常多的数字,以及许多其他领域,如名称等。

students(表格有超过100列,每个单元格可以有一些预先设定的ID,后来被翻译成等级/一些愚蠢的反黑客技术,其中几个数字可以代表相同的等级/)

|| name  || surname|| section || math1||math 2||math 16|| physics 1||physics 2 ||... ||
|| Jonah || Smith  ||  A4     || 17   || 19   || 0     || 193      ||          ||    
|| John  ||Doe     ||  A3     ||  0   || 0    || 34    ||12        ||  0       || ...||
|| Jane  ||Doe     ||  A3     ||  0   || 0    || 48    ||12        ||  154     || ...||
|| Martin||Doe     ||  A3     || 17   || 34   || 96    ||10        || 225      || ...||

可取的结果

|| avg.grade || name  || surname|| section || math1||math 2||math 16|| physics 1||physics 2||... ||
|| 0.92      || John  ||Doe     || A3      ||0   || 0    ||...    ||12        || 0       || ...||
|| 0.81      || Jane  ||Doe     || A3      ||0   || 0    ||...    ||12        || 154     || ...||

除了之外,没有其他相关的表格

  • 内存表中的辅助,具有成绩到ID表示
  • 科目和学生的数据

我希望选择(使用Laravel eloquent模型)所有字段和'最终成绩',所有选定的汇总是什么...高于某个阈值。 (如下所示

SELECT *, a FROM `students` WHERE 
`name` LIKE "J%" AND `surname` LIKE "D" AND `section` = 'A3'
enter code here
AND (if(`math16`='12',0.76, 0)
+if(`geometry26`='13',0.76, 0) +if(`physics13`='325',1, 0)
+if(`programming06`='551',1, 0) +if(`biology18`='271',0.916, 0) 
+ .... )/18.216 as a > 0.75

'12','13','25','551','271' - 是等级代码。

从技术上讲,我需要让所有的学生,或多或少相同的课程,并给出一个特定的起始姓名的平均成绩。 (我的意思是,如果我有约翰,他参加了特定课程[math16,等级0.76,生物学18,等级0.91,...]和简[math16等级0.76,编程06等级100,...],我想在没有其他学生的情况下,将他们的成绩与他们的成绩相加。

也许还有一些其他的可能性可以将所有行以某种相同的字段组合在一起,但我无法理解如何才能这样做。谢谢

php laravel eloquent dynamicquery
1个回答
1
投票

我不建议将主题保留在students表中,而是应该进一步探索规范化数据库并添加subjectsstudent_subject表。但是,对于当前的设置,您可以考虑在模型上创建属性,然后附加它。

https://laravel.com/docs/5.7/eloquent-serialization#appending-values-to-json

class User {

    protected $appends = [
        'average_grade'
    ];

    public function getAverageGradeAttribute()
    {
        return $this->attributes['average_grade'] = ($this->math1 + $this->math2) / 2;
    }

}

这样做只允许您在视图中显示属性时调用该属性,如下所示:

<table>
    <thead>
        <tr>
            <th>Student</th>
            <th>Average Grade</th>
        </tr>
    </thead>
    <tbody>
        @foreach($students as $student)
            <tr>
                <td>{{ $student->name }}</td>
                <td>{{ $student->average_grade }}</td>
            </tr>
        @endforeach
    </tbody>
</table>
© www.soinside.com 2019 - 2024. All rights reserved.