【发布时间】:2016-01-26 18:02:30
【问题描述】:
当我回应这个时:
<?php echo $photo->votesCount ?>
我明白了
[{"photo_id":1,"votes":2}]
如何显示投票 (2)?
这是对象的一个 vardump:http://pastebin.com/ddAkRk4c
如果我输入:
<?php print_r( $photo->votesCount )?>
我明白了:http://pastebin.com/ZfE76WmB
完整视图:
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');
}
【问题讨论】:
-
使用
print_r而不是echo -
添加 print_r() 而不是 var_dump();
-
如果有实际 Laravel 知识的人可以回答,那就太好了 - 必须有一种 Laravel 方法来访问这些值,到目前为止,所有答案似乎都是肮脏的解决方法
-
@Legionar 一定是这里打错了吗?我在我的代码中写