Laravel-找出哪个页面有“;张贴“;在(寻呼)中


Laravel - Find out which page has the "post" in (Pagination)

我正在开发一个"类似论坛"的应用程序,在查看线程时,用户还可以选择查看线程中的帖子(特定帖子)。

URL可以类似于/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

我的示例URL看起来像: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.

怎么能做到这一点?谢谢

将post-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;

以下是我的操作方法:

$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
$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