我要用Laravel创建博客。现在我在博客中得到了post表单类别,我只能根据post显示页面,但是我只想显示与类别id有关系的帖子。
我的代码有一些问题,请帮助我解决我的问题。
在控制器源代码中:
//this code show posts according to category id
$postCatId = $request->postCatId;
$postList =PostCat::with("posts")->where('id',$postCatId)->get();
//this code show paginate according to posts has relation with category
$paginate=PostCat::with("posts")->where('id',$postCatId)->paginate(2);然后返回$postList和$paginate来查看
考虑到:
//show posts has relation with category id
@foreach($PostList as $post)
@foreach($post->posts as $post_item)
{{$post_item->id}}
@endforeach
@endforeach
//show paginate according to posts has relation with category id
{{$paginate->links()}}但是,我不能用与类别id相关的帖子显示分页。
发布于 2017-01-25 12:56:58
如果要对具有类别的帖子进行分页,请使用此查询而不是当前的两个查询:
$posts = Post::with('category')
->has('category')
->where('id', $postCatId)
->paginate(2);确保在category()模型中有Post关系:
public function category()
{
return $this->belongsTo('App\PostCat');
}在视图中,遍历$posts并呈现链接:
@foreach($posts as $post)
<div>Post ID is {{ $post->id }} and category ID is {{ $post->category->id }}</div>
@endforeach
{{ $paginate->render() }}发布于 2017-04-28 22:32:52
在Laravel 5中,对于许多人来说,更简单的方式是建立多种关系,并将其分页如下:
类别模式:
public function articles()
{
return $this->belongsToMany('App\Article');
}条款范本:
public function categories()
{
return $this->belongsToMany('App\Category');
}当您想下载带有分页的类别中的所有帖子/文章时:
$category = Category::where('slug', $slug)->firstOrFail();
$category_articles = $category->articles()->orderBy('created_at', 'desc')->paginate(10);https://stackoverflow.com/questions/41851834
复制相似问题