我有一个典型的模型关系。我有型号QR
,其中hasMany
评级,和一个模型Rating
,其中belongsTo Qr
。Laravel对象关系在foreach循环中不起作用
现在我想输出Ratings
,这属于一个qr
模型,通过foreach
循环是这样的:
<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);
}
这里是我的两个模型
评级.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
计数,QR码了。我知道这是可以做到的它在某种程度上是这样的:
{{Rating::where('qr_id', $qr->id)->count()}}
但我想这样做在某种程度上是这样的foreach
循环
{{ $Qr->rating->count() }}
如果这是某种可能。
我得到的关系,如果我只是输出的Qr
的first()
然后 的var_dump($ qrs-> ratings->指定者())
但我不知道怎么弄的计数额定值与foreach
循环组合在一起。任何帮助将深表感谢。
谢谢。将在几个小时内尝试...现在我的方式,无法测试它。但肯定地感谢你的贡献。 – LoveAndHappiness