我制作了一个自定义和简单的博客模块。
我试图在单篇文章页面上显示下一篇文章和上一篇文章。
然后我尝试在模型帮助下到达
public function onRun (){
$this->articles = $this->getNextArticleAttribute();
$this->articles = $this->getPreviousArticleAttribute();
}
public function getNextArticleAttribute() {
return self::where('id','<', $this->id)->orderBy('id', 'ASC')->first();
}
public function getPreviousArticleAttribute() {
return self::where('id','>', $this->id)->orderBy('id', 'ASC')->first();
在单个页面中
{% set previous = __SELF__.previousArticle() %}
<div class="wrapper-small">
<div id="single-pagination" class="blog-pagination fixed">
<ul class="pagination clearfix">
<li class="prev"><a href="/news/{{previous.slug}}" class="pseudo-ajax">
<span class="text">Précédent</span>
<span class="page-image"><span><img src="{{previous.newsimage.path}}" alt="SEO Name" /></span></span>
</a>
{% set next = __SELF__.nextArticle() %}
</li>
<li class="next "><a href="/news/{{next.slug}}" class="pseudo-ajax">
<span class="text">Suivant</span>
<span class="page-image"><span><img src="{{next.newsimage.path}}" alt="SEO Name" /></span></span>
</a></li>
</ul>
</div> <!-- END .single-pagination -->
</div> <!-- END .wrapper-small -->
所以我真的不知道我在想什么...
答案 0 :(得分:1)
首先,您必须在模型中将previousArticle和nextArticle声明为accessors:
public function getNextArticleAttribute() {
和
public function getPreviousArticleAttribute() {
然后,从您的模型实例中,您可以获取下一篇或上一篇文章,这样:
$model = Article::find($id); // instantiate an article model
$model->nextArticle; // return a model article
$model->previousArticle; // both without parentesis
另一方面,我认为您不需要在两个函数中都调用$post = Article::where('slug',$slug)->first();
,因为$this
实际上是当前文章,因此nextArticle可能看起来像这样:
public function getNextArticleAttribute() {
return self::where('id','>', $this->id)->orderBy('id', 'ASC')->first();
}