当我回应这个时:
<?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');
}
答案 0 :(得分:3)
您无需使用第二种方法votesCount
。您已为投票定义了hasMany
关系,如果您查询它们,则只能获得照片ID的投票。
要获得投票计数,请在您的视图中执行以下操作:
$photo->votes->count();
你的控制器应该是这样的:
$photos = Photo::where('period_id', $currentPeriod)
->with('votes')
->get();
答案 1 :(得分:0)
<?php echo $photos->votesCount->votes ?>
答案 2 :(得分:0)
<?php echo $photos->votesCount->votes ?>
但你也可以写
{{ echo $photos->votesCount->votes; }}
答案 3 :(得分:0)
试试这个:
因为它是一个JSON数组json_decode数组并且回显值
$photo_array = json_decode($photos->votesCount);
echo $photo_array['votes'];
希望这有用。
答案 4 :(得分:0)
您的$photos->votesCount
返回一个字符串,您必须将其转换为如下数组:
$str = $photos->votesCount //gets the string
$arr = json_decode($str, true)[0]; //convert it to an array
echo $arr['votes'];
或作为对象
$str = $photos->votesCount //gets the string
$obj = json_decode($str)[0]; //convert it to an object
echo $obj->votes;
答案 5 :(得分:0)
我成功地进行了这样的测试并得到了回声2:
RewriteEngine on
RewriteCond %{HTTP_HOST} !^www.vitrinsaz1.ir
RewriteRule ^.*$ http://www.vitrinsaz1.ir%{REQUEST_URI} [R=301,L]
RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?/$1 [L,QSA]
所以这对你来说很合适
$str = '[{"photo_id":1,"votes":2}]';
$arr = json_decode($str, true); //convert it to an array
echo $arr[0]["votes"];
如果这不起作用,请尝试将第一行更改为
$str = '$photo->votesCount';
$arr = json_decode($str, true); //convert it to an array
echo $arr[0]["votes"];
答案 6 :(得分:0)
由于它是一个JSON数组,json_decode数组并回显值:
$photo_array = json_decode($photos->votesCount, true);
echo $photo_array[0]['votes'];
不要忘记在true
中添加第二个属性json_decode
- 请参阅manual。
所以整个代码:
<?php
foreach ($photos as $photo) {
echo "<li class='photo'>";
echo "<img src='{{URL::to(\'/\')}}/uploads/{{$photo->name}}' width='150'>";
echo "<div>";
echo "<a href='{{route(\'photos.show\', $photo->id)}}'>{{ $photo->name }}</a>";
$photo_array = json_decode($photo, true);
echo $photo_array[0]['votes'];
echo "</div>";
echo "</li>";
}
?>
答案 7 :(得分:-1)
votesCount是一个数组。所以就像这样回应它
<?php echo $photos->votesCount['votes'] ?>