Laravel - 找出哪个页面中有“帖子”(Pagination)

时间:2016-05-06 23:46:54

标签: php laravel pagination

我正在开发“类似论坛”应用,在查看主题时,用户还可以选择查看主题(特定主题)中的帖子。

网址可以是/thread/29?post=22。现在,一个帖子可以有很多帖子。因此,由于每页有10个帖子,所以帖子可以在任何页面中,具体取决于发布的时间。

我无法知道帖子在帖子中的哪个页面。

注意分页记录是动态的。

我的代码:

$posts = Post::where('thread_id', $thread->id)->paginate(10);
//there are over 50+ posts for instance 

我的简化观点:

@foreach ($posts as $post)

    <span id="post{{ $post->id }}">Post #{{ $post->id }}</span>

    {{ $post->body }}

@endforeach

我的示例网址如下:http://example.com/thread/1

我如何知道哪个页面有特定帖子?假设我想转到ID为28的帖子,该帖子属于ID为1的帖子。我怎么知道该帖子的结果页面是什么?

我想做类似的事情:

http://example.com/thread/1?post=28&page=2 //authomatically guessed that post 28 would be in page 2.

怎么办呢? 谢谢!

3 个答案:

答案 0 :(得分:0)

将帖子ID除以10和ceil值。当然,如果线程中的每个帖子都以1开头并以1递增。

$page = ceil($post->id / 10);

修改

如果您的帖子ID是动态的,则检索按帖子日期排序的帖子中的所有帖子,并迭代结果以查找搜索到的ID的位置。我不是一个laravel开发人员,所以不确定查询语法,但是像这样:

$searching_id = 28; // searching for page of post id 28
$post_index = 0;    // position of post in ordered posts array
$posts = Post::where('thread_id', $thread->id)->order_by('post_date'); // get all posts ordered by post_date or whatever table field is for post date
foreach ($posts as $post) {
    if ($post->id == $searching_id) {
        break;
    }
    $post_index++;
}
$page = (int)($post_index / 10) + 1;

答案 1 :(得分:0)

继承人我是怎么做到的:

$post_id = 28;
$posts_per_page = 10;
$posts = Post::where('id', $thread->id)->get();

foreach ($posts as $key => $value) {
    if ($value->id == $post_id) {
        $page = ceil(($key + 1) / $posts_per_page);
        break;
    }
}

// $page = 2

答案 2 :(得分:0)

$post_id = 28;
$posts_per_page = 10;
$posts = Post::where('id', $thread->id)->get(['id'])->flip();
$index = $posts[$post_id]

$page = ((int) ($index / $posts_per_page) + 1