我正在使用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
的网址,其中片段是回复ID。我想不出来,有什么想法吗?在使用Call to undefined method Illuminate\Database\Eloquent\Collection::paginate()
尝试计算线程的页数时,我也会收到错误$thread->replies->paginate(10)
,但这会引发另一个与其他网页上链接的帖子有关的问题。
有没有人有任何想法?
答案 0 :(得分:1)
刚遇到类似的问题。试试这个:
threads.model
// 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/
The original link no longer works. Click here to visit the Google cached version
希望我已将此翻译成您的情况。您可能想要查看链接,它比我更有用。
答案 1 :(得分:0)
您没有提供足够的代码来提供详细的响应,但是为了举例并假设您使用了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()方法。