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

Posted Sky_sunkang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 />";
        }
    }

 

以上是关于Laravel5.1 模型--查询作用域的主要内容,如果未能解决你的问题,请参考以下文章

Laravel5.1 模型--查询

二十PHP框架Laravel学习笔记——模型的作用域

JS作用域作用域链

JS 作用域及作用域链

JS 作用域及作用域链

laravel 本地作用于 模型查询