当我回应这个时:
<?php echo $photo->votesCount ?>
我明白了
[{"photo_id":1,"votes":2}]
如何显示投票 (2)?
这是对象的 vardump:http://pastebin.com/ddAkRk4c
如果我输入:
<?php print_r( $photo->votesCount )?>
我明白了:http://pastebin.com/ZfE76WmB
完整 View :
2 @foreach($photos as $photo)
3 <li class='photo'>
4 <img src="{{URL::to('/')}}/uploads/{{$photo->name}}" width="150">
5 <div>
6 <a href="{{route('photos.show',$photo->id)}}">{{ $photo->name }}</a>
7 <?php $photo_array = json_decode($photo);
8 echo $photo_array->votes; ?>
9 </div>
10 </li>
11 @endforeach
部分 Controller 逻辑:
$photos = Photo::where('period_id', $currentPeriod)
->with('votesCount')
->get();
return view('home', ['uploaded' => $uploaded, 'photos' => $photos, 'period' => $currentPeriod]);
型号:
public function votes()
{
return $this->hasMany('App\Vote');
}
public function votesCount()
{
return $this->votes()
->selectRaw('photo_id, count(*) as votes')
->groupBy('photo_id');
}
最佳答案
不需要第二种方法votesCount
。您已经为投票定义了一个 hasMany
关系,如果您查询它们,您只会获得照片 ID 的投票。
要获取票数,请在您的 View 中执行以下操作:
$photo->votes->count();
你的 Controller 应该是这样的:
$photos = Photo::where('period_id', $currentPeriod)
->with('votes')
->get();
关于php - 我该如何回应这个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33366067/