Laravel5.1 模型--查询作用域

所谓的查询作用域就是允许你自定义一个查询语句 把它封装成一个方法。


 1 定义一个查询作用域

定义查询作用域就是在模型中声明一个scope开头的方法:

    public function scopeHotArticle($query)
    {
        return $query->orderBy('comment_count','desc')->first();
    }

然后可以这样使用:

    public function getIndex()
    {
        $hot = Article::hotArticle();
        dd($hot);
    }

 2 动态的查询作用域

动态作用域是允许你传入参数的,根据参数来返回具体的逻辑。

    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 "<br />";
        }
    }
原文地址:https://www.cnblogs.com/sun-kang/p/7523563.html