我有两个模特,第一个:
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
但我所有的&lt; span&gt;是空的!
更新:如果我这样做:
@foreach($tutorials as $tutorial)
@foreach($tutorial->ratings as $rate)
<span>{{$rate->value}}</span>
@endforeach
一切都很好......那么错了吗?
答案 0 :(得分:2)
根据您所在站点的平台,您应始终使用正确的案例。
$tutorials = tutorial::orderBy(...) // Wrong
$tutorials = Tutorial::orderBy(...) // Correct
要急切加载评级,您应该先在其他任何方面声明“使用”方法。
$tutorials = Tutorial::with('rating')
->orderBy('created_at', 'DESC')
->paginate(25);
出于某种原因,这已被排除在L4文档之外。
在您看来,您现在可以使用此
访问评级foreach($tutorials as $tutorial)
{
echo $tutorial->rating->{rating table column name};
}
答案 1 :(得分:0)
首先,就命名惯例而言,为了让事情更容易理解:教程方法中的rating()
方法应该被称为ratings()
,所以当你获得评分时,它看起来会更好($tutorial->ratings
)
重命名后,在您的视图中,在循环浏览$ tutorials数组时,您可以像这样访问每个的评级:
foreach($tutorials as $tutorial)
{
$ratings = $tutorial->ratings;
}
哪个会检索每个的评级对象。
您应该知道的是如果您需要返回评级的计算而不是ORM对象,则可以为模型创建属性
例如,如果每个评级是amount
列中存储的评级表中1-5的数字,您可以执行此操作以将每个评级的平均值设置为属性:
class Tutorial extends Eloquent {
protected $table = '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)
{
$summedRatings += $rating->amount;
}
// Return the calculated average
return $summedRatings / count($ratings);
}
}
然后在您的视图中,您可以回显该属性,就好像它是数据库的一部分
foreach($tutorials as $tutorial)
{
echo $tutorial->rating;
}