我有两个模型,第一个:
class Tutorial extends Eloquent {
protected $table = 'tutorials';
public function rating()
{
return $this->hasMany('Rating');
}
}
和:
class Rating extends Eloquent {
protected $table = 'ratings';
public $timestamps = false;
public function tutorial()
{
return $this->belongsTo('Tutorial');
}
}
现在在我的控制器中我有这个:
public function get_index() {
$tutorials = tutorial::orderBy('created_at', 'desc')
->with('rating')
->paginate(25);
return View::make('site/home/index')->with('tutorials', $tutorials);
}
那么我如何从我的视图中的一个教程中获得所有评级?!
编辑:
现在我有这个:
public function ratings()
{
return $this->hasMany('Rating');
}
public function getRating()
{
// Grab the ratings from this tutorial
$ratings = $this->ratings;
$summedRatings = 0;
// Loop through them all and add them together
foreach($ratings as $rating)
{
console.log($rating->value);
$summedRatings += $rating->value;
}
// Return the calculated average
return $summedRatings / count($ratings);
}
public function get_index() {
$tutorials = Tutorial::with('ratings')
->with('user')
->orderBy('created_at', 'desc')
->paginate(25);
return View::make('site/home/index')->with('tutorials', $tutorials);
}
在我看来:
@foreach($tutorials as $tutorial)
<span>{{$tutorial->rating}}</span>
@endforeach
但是我所有的<span>都是空的!
更新:如果我这样做:
@foreach($tutorials as $tutorial)
@foreach($tutorial->ratings as $rate)
<span>{{$rate->value}}</span>
@endforeach
一切都很好......那么有什么问题吗?