【发布时间】:2014-06-11 12:13:28
【问题描述】:
我有一个典型的模型关系。我有模型QR,hasMany Rating,还有模型Rating,belongsTo Qr。
现在我想通过这样的foreach 循环输出属于单个qr 模型的Ratings:
<table>
<tr>
<th>ID</th>
<th>UnitID</th>
<th># of Ratings</th>
</tr>
@foreach($qrs as $qr->ratings)
<tr>
<td>{{$qr->id}}</td>
<td>{{$qr->unit_id}}</td>
<td>{{$qr->ratings->count()}}</td>
</tr>
@endforeach
</table>
这是我的控制器:
public function index()
{
//
$unit = Unit::all()->first();
$qrs = Qr::all()->first();
return View::make('index')
->with('unit', $unit)
->with('qrs', $qrs);
}
这是我的两个模型
Rating.php:
class Rating extends \Eloquent {
protected $guarded = [];
public function qr(){
return $this->belongsTo('Qr');
}
}
Qr.php:
class Qr extends \Eloquent {
protected $guarded = [];
public function unit(){
return $this->belongsTo('Unit');
}
public function ratings(){
return $this->hasMany('Rating');
}
}
我实际上想输出ratings 的计数,这是一个二维码。我知道可以这样做:
{{Rating::where('qr_id', $qr->id)->count()}}
但我想在 foreach 循环中以某种方式这样做
{{ $Qr->rating->count() }}
如果这是可能的。
我得到了关系,如果我只输出Qr 的first() 然后
var_dump($qrs->ratings->toArray())
但我不知道如何结合foreach 循环来获得评分数。任何帮助将不胜感激。
【问题讨论】:
标签: php html oop laravel eloquent