首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >根据关系表中的数据在laravel显示分页

根据关系表中的数据在laravel显示分页
EN

Stack Overflow用户
提问于 2017-01-25 12:36:37
回答 2查看 763关注 0票数 1

我要用Laravel创建博客。现在我在博客中得到了post表单类别,我只能根据post显示页面,但是我只想显示与类别id有关系的帖子。

我的代码有一些问题,请帮助我解决我的问题。

在控制器源代码中:

代码语言:javascript
复制
//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来查看

考虑到:

代码语言:javascript
复制
//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相关的帖子显示分页。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-01-25 12:56:58

如果要对具有类别的帖子进行分页,请使用此查询而不是当前的两个查询:

代码语言:javascript
复制
$posts = Post::with('category')
             ->has('category')
             ->where('id', $postCatId)
             ->paginate(2);

确保在category()模型中有Post关系:

代码语言:javascript
复制
public function category()
{
    return $this->belongsTo('App\PostCat');
}

在视图中,遍历$posts并呈现链接:

代码语言:javascript
复制
@foreach($posts as $post)
    <div>Post ID is {{ $post->id }} and category ID is {{ $post->category->id }}</div>
@endforeach

{{ $paginate->render() }}
票数 0
EN

Stack Overflow用户

发布于 2017-04-28 22:32:52

在Laravel 5中,对于许多人来说,更简单的方式是建立多种关系,并将其分页如下:

类别模式:

代码语言:javascript
复制
public function articles()
{
    return $this->belongsToMany('App\Article');
}

条款范本:

代码语言:javascript
复制
public function categories()
{
    return $this->belongsToMany('App\Category');
}

当您想下载带有分页的类别中的所有帖子/文章时:

代码语言:javascript
复制
$category = Category::where('slug', $slug)->firstOrFail();
$category_articles = $category->articles()->orderBy('created_at', 'desc')->paginate(10);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41851834

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档