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

觉得上面的内容有用吗?快来点个赞吧!

点赞() 我要打赏

温馨提示 : 本站内容来自会员投稿以及互联网,所有源码及教程均为作者总结编辑,请大家在使用过程中提前做好备份,以免发生无法预知的错误,源码类教程请勿直接用于生产环境!

 可能感兴趣的文章