问题描述
像我们可以渴望加载一个有说服力的模型的关系,有没有办法渴望加载一个方法,这不是一个有力的模型的关系方法?例如,我有一个雄辩模型 GradeReport
,它有以下方法:
public function totalScore()
{
return $ scores = DB :: table('grade_report_scores') - >其中('grade_report_id',$ this-> id) - & ('得分了');
}
现在我收集了一个 GradeReport
雄辩模特。
$ gradeReports = GradeReport :: where('student_id',$ studentId) - > get();
我如何加载 totalScore $ c $的返回值c>方法全部
GradeReport
集合中的雄辩模型
您可以通过将其添加到 $ appends 数组并提供一个getter来为模型添加任意属性。在你的情况下,以下应该做的诀窍:
class GradeReport extends Model {
protected $ appends = ['totalScore ];
public function getTotalScoreAttribute(){
return $ scores = DB :: table('grade_report_scores') - >其中('grade_report_id',$ this-> id) - >总和( '得分');
}
}
现在,从控制器返回的所有GradeReport对象将具有totalScore属性集。
Like we can eager load a relationship of an Eloquent model, is there any way to eager load a method which is not a relationship method of the Eloquent model?
For example, I have an Eloquent model GradeReport
and it has the following method:
public function totalScore()
{
return $scores = DB::table('grade_report_scores')->where('grade_report_id', $this->id)->sum('score');
}
Now I am getting a collection of GradeReport
Eloquent models.
$gradeReports = GradeReport::where('student_id', $studentId)->get();
How can I eager load the returning values of totalScore
method for all GradeReport
Eloquent models in the collection?
You can add arbitrary properties to your models by adding them to $appends array and providing a getter. In your case the following should do the trick:
class GradeReport extends Model {
protected $appends = ['totalScore'];
public function getTotalScoreAttribute() {
return $scores = DB::table('grade_report_scores')->where('grade_report_id', $this->id)->sum('score');
}
}
Now all GradeReport objects returned from your controllers will have totalScore attribute set.
这篇关于Laravel - 渴望加载雄辩模型的方法(而不是关系)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!