控制器:
$users = DB::table('users')
->join('uploads', 'users.id', '=', 'uploads.user_id')
->select(DB::raw('users.*, COUNT(*) AS total_uploads'))
->orderby('total_uploads', 'desc')
->groupby('users.id')
->take(5)
->get();
查看:
<?php $i = 1 ?>
@foreach($users as $user)
<tr>
<td>{{ $i }}</td>
<td><a href="user/{{ $user->username }}">{{ $user->username }}</a></td>
<td>{{ $user->total_uploads }}</td>
</tr>
<?php $i++ ?>
@endforeach
预期输出:
1 John 99
2 Mary 78
3 Jill 57
3 Bill 57
5 Hans 56
如何修改此项以说明关系?
答案 0 :(得分:1)
试试这个:
<?php $i = 0;
$last_count = null;
?>
@foreach($users as $user)
<?php if($user->total_uploads != $last_count) $i++; ?>
<tr>
<td>{{ $i }}</td>
<td><a href="user/{{ $user->username }}">{{ $user->username }}</a></td>
<td>{{ $user->total_uploads }}</td>
</tr>
<?php $last_count = $user->total_uploads; ?>
@endforeach
只有当前用户total_uploads
与上一位用户的total_uploads
不同时,该计数器才会递增。