本文实例讲述了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 />";
    }
  }