php - 根据laravel中关系表中的数据显示分页

标签 php mysql laravel laravel-5 pagination

我打算在 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/

相关文章:

php - 计算MySQL查询时的时间差

javascript - 获取某个模型相关的所有集合记录

mysql - 通过索引获取列名并在mysql查询中使用

php - 无法连接到 mysql - 在 InMotion 托管上使用 PHP 7.1 设置 Laravel 5.8 时出错。多 PHP 版本

php - eval() 不返回函数结果

PHP - 检查日期 ID 并插入数据

javascript - 模块构建失败 : Error: write EPIPE (or make processCssUrls:false) in css imports Laravel Mix

php - Laravel:如何在嵌套的 hasMany 关系上取平均值(hasManyThrough)

php - 默认的 mb_internal_encoding() 值来自哪里?

mysql - 合并具有唯一列的两个表条目 (MySQL)