首页 > 解决方案 > Laravel:如何计算模型中的总分并使用 with 函数将结果作为 JSON 返回

问题描述

我有名为考试的表

  Schema::create('exams', function (Blueprint $table) {
        $table->increments('id');
        $table->integer ('theory_score');
        $table->integer ('theory_coefficient');
        $table->integer ('practical_score');
        $table->integer ('practical_coefficient');
        $table->date('exam_date');

我想在我的模型考试中创建一个函数 totalMarks() 来计算考试的总分,就像这样

class Exam extends Model
    {
     protected $guarded = [];
   public function student() {
    return $this->belongsTo('App\Student', 'student_id', 'id');
   }
   public function totalMarks(){
     return (($this->theory_score*$this->theory_coefficient)+($this->practical_score*$this->practical_coefficient))/100;
   }

我想使用以下函数进行这样的查询

 public function getExam($studentId)
   {
     $exam = Exam::where('student_id','=',$studentId)
     ->with('student','totalMarks')->get()->toJson();
   return $exam; 
   }

我有这个错误

"message": "在整数上调用成员函数 addEagerConstraints()", "exception": "Symfony\Component\Debug\Exception\FatalThrowableError",

标签: angularjsjsonlaravel

解决方案


您可以使用访问器来完成这项工作:

class Exam extends Model
{

    public function student() {
        return $this->belongsTo(App\Student::class, 'student_id', 'id');
    }

    public function getTotalMarksAttribute() {
        return (($this->theory_score*$this->theory_coefficient)+($this->practical_score*$this->practical_coefficient))/100;
    }
...

如果您想在从数据库中获取模型时计算此值,请使用retrieved事件(以下代码属于模型本身):

protected static function boot()
{
    parent::boot();

    static::retrieved(function($exam) {
        $exam->attributes['total_marks'] = $exam->total_marks;
    });
}

为了检索您使用的计算属性

  1. Exam::where(..)->first()->total_marks // single exam
  2. Exam::where(..)->get()->pluck('total_marks') // collection of exams

推荐阅读