【发布时间】:2017-07-06 16:45:09
【问题描述】:
我正在尝试在 laravel 中实现分页并得到以下错误
Undefined property: Illuminate\Pagination\LengthAwarePaginator::$name
这是我的控制器功能
public function showTags($id)
{
$tag = Tag::find($id)->paginate(5);
// when lazy loading
$tag->load(['posts' => function ($q) {
$q->orderBy('id', 'desc');
}]);
return view('blog.showtags')->withTag($tag);
}
这是标签模型
class Tag extends Model
{
public function posts()
{
return $this->belongsToMany('App\Post');
}
}
Tag 和 Post 模型具有 belongsToMany 关系,因此特定标签下有很多帖子,我的目标是迭代特定标签下的所有帖子,并在该页面中实现分页。
这里是 showtags 视图的代码
<table class="table">
<thead>
<tr>
<th>#</th>
<th>Title</th>
<th>Tags</th>
</tr>
</thead>
<tbody>
<?php $count = 1; ?>
@foreach($tag->posts as $post)
<tr>
<th>{{ $count++ }}</th>
<th>{{ $post->title }}</th>
<th>@foreach($post->tags as $tag)
<span class="label label-default">{{ $tag->name }}</span>
@endforeach
</th>
</tr>
@endforeach
</tbody>
</table>
//Here is the code i used for pagination in view
<div class="text-center">
{!! $tag->posts->links() !!}
</div>
如果有人知道该怎么做,请回复。提前致谢。
【问题讨论】:
-
不确定我是否遗漏了一些东西,但
find只得到一行,所以你不能对其进行分页。你想做什么? -
@apokryfos 我知道 find 只给出一行,但在我看来,我在同一个标签下迭代每个帖子,因为标签与帖子有很多关系。我的目标是通过分页组织同一标签下的所有帖子。那么有没有办法做到这一点
-
所以你可能会做类似
$tag->posts()->paginate(5)或类似的事情。 -
函数
showTags($id)中的$id是一个标签ID。对吗? -
@apokryfos 感谢您的建议,我在视图中将 $tag->posts->links() 替换为 $tag->posts()->paginate(5) 并从视图中删除错误并控制器的轻微修改相应地帮助我解决问题。
标签: php laravel pagination laravel-5.4