【问题标题】:show paginate according to data in relation table in laravel根据laravel中关系表中的数据显示分页
【发布时间】:2017-05-01 08:48:18
【问题描述】:

我将在 Laravel 中创建博客。现在我在博客中获得了帖子表单类别,我只能根据帖子显示分页,但我只想为与类别 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 相关的帖子的分页

【问题讨论】:

  • 您想对所有有分类的帖子进行分页?因为现在您正在对类别进行分页,而不是帖子。
  • 没错,这段代码只为类别分页,但我想根据帖子显示分页与类别有关系

标签: php mysql laravel laravel-5 pagination


【解决方案1】:

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

$posts = Post::with('category')
             ->has('category')
             ->where('id', $postCatId)
             ->paginate(2);

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

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() }}

【讨论】:

  • 不,我认为它是错误的,因为这段代码:$posts = Post::with('category') ->has('category') ->where('id', $postCatId) - >分页(2);只显示分类分页
  • 不,此代码获取所有具有类别的帖子并忽略没有类别的帖子。然后是分页结果(分页帖子)。
【解决方案2】:

在 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-03
    • 2018-02-01
    • 1970-01-01
    • 2020-06-03
    • 2019-09-04
    • 2021-02-09
    • 1970-01-01
    相关资源
    最近更新 更多