我有一个名为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”,
答案 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;
});
}
为了检索您使用的计算属性
Exam::where(..)->first()->total_marks // single exam
Exam::where(..)->get()->pluck('total_marks') // collection of exams