在 Laravel 中为 Eloquent 模型添加自定义方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17371009/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding custom methods to Eloquent Model in Laravel
提问by James Jeffery
I have an Eloquent Article model in my Laravel 4 app. It's empty at the moment, but what I want to do is define two methods:
我的 Laravel 4 应用程序中有一个 Eloquent Article 模型。目前它是空的,但我想做的是定义两个方法:
- getNextArticle
- getPreviousArticle
- 获取下一篇文章
- 获取上一篇
So that when I use:
所以当我使用:
$article = Article::find(1);
I can follow up with:
我可以跟进:
$article->getNextArticle;
and
和
$article->getPreviousArticle;
I need to get access to the results returned from find() within the Articles model so I can use the data to get the next and previous articles from an SQL query.
我需要访问从文章模型中的 find() 返回的结果,以便我可以使用数据从 SQL 查询中获取下一篇和上一篇文章。
Theoretically I end up with something like:
从理论上讲,我最终会得到类似的结果:
class Article extends Eloquent
{
public function getNextArticle()
{
// SQL query to get next article from the database
}
public function getPreviousArticle()
{
// SQL query to get previous article from the database
}
}
回答by deyes
Class Article extends Eloquent {
public function getNextArticle()
{
return Article::where('id', '>', $this->id)->take(1)->get();
}
public function getPreviousArticle()
{
return Article::where('id', '<', $this->id)->take(1)->get();
}
}
回答by ronscript
Source Laravelhttp://laravel.com/docs/4.2/eloquent
源 Laravel http://laravel.com/docs/4.2/eloquent
Article is redundant so i removed it.
文章是多余的,所以我删除了它。
Class Article extends Eloquent {
public function scopeNext($query)
{
return $query->where('id', '>', $this->id)->take(1)->get();
}
public function scopePrevious($query)
{
return $query->where('id', '<', $this->id)->take(1)->get();
}
}
回答by Kylie
I would probably try it like this... not sure if it would work though
我可能会像这样尝试......但不确定它是否有效
class Article extends Eloquent
{
public function getNextArticle()
{
return Article::find($this->id+1)->get();
}
public function getPreviousArticle()
{
return Article::find($this->id-1)->get();
}
}