【问题标题】:Laravel - Find out which page has the "post" in (Pagination)Laravel - 找出哪个页面在(分页)中有“帖子”
【发布时间】:2016-05-06 23:46:53
【问题描述】:

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

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.

如何做到这一点? 谢谢!

【问题讨论】:

  • 你能解释一下吗?您是否有包含帖子或仅帖子的线程并且您希望它们被订购或什么?我无法理解问题!您希望订单显示为已订购吗?我的意思是从第 1 页的 1 到 10 以及从第 2 页的 11 到 20 等?
  • 是的,我希望订购它们。所以就像一个线程在许多页面上有很多帖子,我想找出哪个页面有帖子

标签: php laravel pagination


【解决方案1】:

将帖子 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;

【讨论】:

  • 对不起,我应该提一下分页记录是动态的。
  • 谢谢,我以类似的方式完成了它,但它 90% 喜欢你的解决方案。
【解决方案2】:

我是这样做的:

$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

【讨论】:

    【解决方案3】:
    $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
    

    【讨论】:

    • 虽然这段代码 sn-p 可以解决问题,但它没有解释为什么或如何回答这个问题。请include an explanation for your code,因为这确实有助于提高您的帖子质量。请记住,您正在为将来的读者回答问题,而这些人可能不知道您的代码建议的原因。您可以使用edit 按钮改进此答案以获得更多选票和声誉!
    猜你喜欢
    • 2014-10-26
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 2019-04-15
    • 2015-12-15
    • 2019-05-14
    相关资源
    最近更新 更多