I have a typical model relation. I have the model QR
, which hasMany
Rating, and a Model Rating
, which belongsTo Qr
.
Now I want to output the Ratings
, which belong to a single qr
model, through a foreach
loop like this:
<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>
This is my Controller:
public function index()
{
//
$unit = Unit::all()->first();
$qrs = Qr::all()->first();
return View::make('index')
->with('unit', $unit)
->with('qrs', $qrs);
}
Here are my two Models
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');
}
}
I actually want to output the count of ratings
, a Qr-Code has. I know it is possible to do it somehow like this:
{{Rating::where('qr_id', $qr->id)->count()}}
But I want to do it somehow like this in the foreach
loop
{{ $Qr->rating->count() }}
If this is somehow possible.
I get the relation, if I just output the first()
of Qr
and then
var_dump($qrs->ratings->toArray())
But I don't know how to get the count Number of ratings in combination with the foreach
loop. Any help would be dearly appreciated.