我正在尝试获取项目中的上一个和下一个记录(如博客文章)。我无法获取与每个项目的相关的ID。
我可以在我的projectController中的同一查询中这样做吗?
我可以分配并获取每个项目的标题,这些标题是根据标题创建的。
::ProjectController
public function single($slug){
$project = Project::with('tools', 'categories')->where('slug', $slug)->firstOrFail();
$prev = Project::where('id', '<', $project->id)->orderBy('id','desc')->first();
$next = Project::where('id', '>', $project->id)->orderBy('id')->first();
return view('project-single',compact('project',$project))
->with('prev',$prev)
->with('next',$next);
}
::SingleProject.blade.php
@if($prev ==! null)
<a href="{{ route('project.single', ['project' => $prev]) }}" class="animate">
<i class="las la-long-arrow-alt-left"></i>Anterior
</a>
@endif
::Route
Route::get('/proyectos/{slug}', 'ProjectController@single')->name('project.single');
答案 0 :(得分:0)
那呢:
$project = Project::with('tools', 'categories')->where('slug', $slug)->firstOrFail();
$more = Project::whereIn('id', [$project->id - 1, $project->id + 1])->get();
$prev = $more->where('id', '<', $project->id)->first();
$next = $more->where('id', '>', $project->id)->first();
答案 1 :(得分:0)
我解决了这个问题:
::projectController
public function single($slug){
$project = Project::with('tools', 'categories')->where('slug', $slug)->firstOrFail();
$next = Project::where('id', '>', $project->id)->min('id');
$prev = Project::where('id', '<', $project->id)->max('id');
return view('project-single',compact('project',$project))
->with('prev',Project::find($prev))
->with('next',Project::find($next));
}
:::view
@if($prev ==! null)
<a href="{{ route('project.single', ['slug' => $prev->slug]) }}" class="animate">
<i class="las la-long-arrow-alt-left"></i>Anterior
</a>
@endif