【发布时间】:2015-05-23 05:05:19
【问题描述】:
我正在构建一个基本论坛(受laracasts.com/discuss 启发)。当用户回复某个话题时:
- 我想用他们的回复锚点将他们引导到分页回复列表的末尾(与 Laracast 的行为相同)。
- 我还想在用户编辑其中一个回复时将其返回到正确的页面。
如何确定新回复将发布在哪个页面 (?page=x) 以及在编辑回复后如何返回正确的页面?或者,从主帖子列表中,最新回复在哪个页面上?
这是我目前的ForumPost 模型(减去一些不相关的东西)-
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
/**
* Class ForumPost
*
* Forum Posts table
*
* @package App
*/
class ForumPost extends Model {
/**
* Post has many Replies
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function replies()
{
return $this->hasMany('App\ForumReply');
}
/**
* Get the latest reply for a post
* @return null
*/
public function latestReply()
{
return $this->replies()->orderBy('created_at', 'desc')->first();
}
}
更新
看看这个,让我知道你的想法。它的工作方式有点奇怪,但它会为给定的回复 ID 返回正确的页面,这只是一种方法:
public function getReplyPage($replyId = null, $paginate = 2)
{
$id = $replyId ? $replyId : $this->latestReply()->id;
$count = $this->replies()->where('id', '<', $id)->count();
$page = 1; // Starting with one page
// Counter - when we reach the number provided in $paginate, we start a new page
$offset = 0;
for ($i = 0; $i < $count; $i++) {
$offset++;
if ($offset == $paginate) {
$page++;
$offset = 0;
}
}
return $page;
}
【问题讨论】:
-
评论您的更新:
$count % $paginate将返回$count/$paginate的剩余 ($offset),因此11%2 = 1,这将为您提供偏移量。可以使用floor($count / $paginate).. 来检查 pageno。可能会有一点改进。 -
是的,谢谢.. 那是深夜编码,涉及到一点点酒;)我认为感谢@MirroredFate,我走在正确的轨道上,但我仍然想知道伟大的 Jeffrey Way 是如何完成的这。从那以后,我发现其他一些人试图在没有太多运气的情况下解决这个问题。主要想知道实现这一点的最有效方法实际上是什么,不确定对我的列表中的每个 Post 对象运行这些查询会产生什么样的性能影响
标签: php laravel laravel-5 laravel-pagination