我打算在 Laravel 中创建博客。现在我在博客中获得帖子表单类别,我只能根据帖子显示分页,但我只想为与类别 ID 有关系的帖子显示分页
我的代码有问题,请帮助我解决问题。
在 Controller 源代码中:
//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
来查看
在 View 中:
//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 相关的帖子分页
最佳答案
如果您想对具有类别的帖子进行分页,请使用此查询而不是当前的两个查询:
$posts = Post::with('category')
->has('category')
->where('id', $postCatId)
->paginate(2);
确保在 Post
模型中有 category()
关系:
public function category()
{
return $this->belongsTo('App\PostCat');
}
在 View 中遍历 $posts
并呈现链接:
@foreach($posts as $post)
<div>Post ID is {{ $post->id }} and category ID is {{ $post->category->id }}</div>
@endforeach
{{ $paginate->render() }}
关于php - 根据laravel中关系表中的数据显示分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41851834/