[英]Manipulating data within an object
嗨,我是Laravel和php的新手。 在我的數據庫中,每個學生在每個科目上都有三個分數,我需要檢索它們並將每個學生的平均分數發送到視圖。 我嘗試如下進行操作,但是返回的值是一個對象(例如[5,4,3]),並且不允許我計算平均值。 請告知我如何處理對象中的數據。
$students = Student::all();
foreach ($students as $student) {
$mathPoints = Point:: where('subject_id', 1)
->where('student_id', $student->id)
->pluck('points');
}
我嘗試通過(array)方法將其轉換為數組,但之后無法使用array_sum計算值的總和。
更新:我的Point模型:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Point extends Model
{
//Get the student the credit points are related to
public function student()
{
return $this->belongsTo('App/Models/Student');
}
//Get the subject the credit points are related to
public function subject()
{
return $this->belongsTo('App/Models/Subject');
}
}
Point::where('student_id', $student->id)->get()
當您對Eloquent使用all()
時,它將為您查詢。 如果使用where()
,則必須先使用get()
“獲取”它,然后才能將其用作集合。
$mathPoints = Point::where('student_id', $student->id)
->get()
->pluck('points');
但是,我可能會考慮使用更復雜的查詢來獲取此數據,因為您很容易最終每頁而不是僅僅進行數百次查詢。
使用Model::avg('columnName')
計算平均值。
在此處閱讀更多信息: https : //laravel.com/docs/5.4/queries#aggregates
$students = Student::all();
foreach ($students as $student){
$mathPoints = Point::where(['subject_id'=>1,'student_id'=>$student->id])->avg('points');
$student->avgPoint=$mathPoints;
}
刀片內:
{{ $student->avgPoint}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.