Laravel:生成分页项目的URL


Laravel: Generate URL to paginated item

我正在使用Laravel 5构建一个讨论论坛。每个论坛都有帖子,每个帖子都有回复。我找不到任何关于如何获得帖子最新回复的URL的信息——现在我有这个功能可以向论坛展示:

public function show($slug)
{
    $forum = $this->forums->getBySlug($slug);
    return view('forum.show', compact('forum'));
}

然后在该视图中,我有一个基本的@forelse来显示与HasMany相关的线程:

@forelse($forum->threads as $thread)
    <tr>
        <td><a href="{{ route('forum.thread', [$forum->slug, $thread->slug]) }}">{{ $thread->title }}</a></td>
        <td>{{ $thread->replies->count() }} Replies</td>
        <td>{{ $thread->replies->last()->author->username or 'No recent activity' }}</td>
    </tr>
@empty
    <tr>
        <td colspan="3" class="text-center">There aren't any threads in this forum</td>
    </tr>
@endforelse

这很好,但我希望最近回复的用户名与实际回复链接,并使用类似http://example.com/forum/thread-title-here/?page=3#12345的url,其中片段是回复ID。我想不通,有什么想法吗?当使用$thread->replies->paginate(10)尝试计算线程的页数时,我也得到了错误Call to undefined method Illuminate'Database'Eloquent'Collection::paginate(),但这带来了关于链接到其他页面的帖子的另一个问题。

有人有什么想法吗?

刚刚遇到类似的问题。试试这个:

螺纹.型号

// probably what you have now
public function replies() { return hasMany('Reply');}

您可以向回复模型添加第二个关系,如下所示:

// add this relation which has a filter
public function latestReply() { return hasOne('Reply')->last();}

现在,当你想要最新的回复时,你可以这样做:

$forum = $this->forums->getBySlug($slug)->with('threads','threads.latestReply');

在您看来: @foreach($forum->threads as $thread) {{$thread->latestReply->id}} @endforeach

我从中学到了这一点http://softonsofa.com/tweaking-eloquent-relations-how-to-get-latest-related-model/

原来的链接已不起作用。点击此处访问谷歌缓存版本

希望我已经把这个翻译成你的情况。你可能想查看链接,它比我的信息更丰富。

您没有提供足够的代码来给出详细的响应,但为了举个例子,并假设您使用Laravel的命名约定:

// Eager load threads and their replies
$forum = Forum::with(array('threads.replies' => function($q) {
    // For each thread, get the most recent reply
    $q->orderBy('some_date_column', 'desc')->take(1);
}))->get();

从您提供的代码来看,似乎需要修改getBySlug()方法。