1 定义一个查询作用域
定义查询作用域就是在模型中声明一个scope开头的方法:
public function scopeHotArticle($query)
{
return $query->orderBy('comment_count','desc')->first();
}然后可以这样使用:
public function getIndex()
{
$hot = Article::hotArticle();
dd($hot);
}动态作用域是允许你传入参数的,根据参数来返回具体的逻辑。
public function scopeCommentMoreThan($query, $comment)
{
return $query->where('comment_count','>',$comment);
}
public function getIndex()
{
$articles = Article::commentMoreThan(10)->orderBy('comment_count', 'desc')->get();
foreach ($articles as $article){
echo $article->title . ' ' . $article->comment_count;
echo "
";
}
}