Laravel:如何使用The with函数在Model中计算总分数并以JSON形式返回结果

时间:2018-06-21 07:42:26

标签: angularjs json laravel

我有一个名为Exam的表

  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”,

1 个答案:

答案 0 :(得分:1)

您可以使用accessor来完成这项工作:

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