当前位置:首页 > CMS教程 > 其它CMS > 列表

Laravel5.1 框架模型查询作用域定义与用法实例分析

发布:smiling 来源: PHP粉丝网  添加日期:2022-02-03 20:35:52 浏览: 评论:0 

本文实例讲述了Laravel5.1 框架模型查询作用域定义与用法,分享给大家供大家参考,具体如下:

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

1 定义一个查询作用域

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

  1. public function scopeHotArticle($query) 
  2. { 
  3.   return $query->orderBy('comment_count','desc')->first(); 
  4. } 

然后可以这样使用:

  1. public function getIndex() 
  2. { 
  3.   $hot = Article::hotArticle(); 
  4.   dd($hot); 
  5. } 

2 动态的查询作用域

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

  1. public function scopeCommentMoreThan($query, $comment) 
  2. { 
  3.   return $query->where('comment_count','>',$comment); 
  4. } 
  5.  
  6. public function getIndex() 
  7. { 
  8.   $articles = Article::commentMoreThan(10)->orderBy('comment_count', 'desc')->get(); 
  9.   foreach ($articles as $article){ 
  10.     echo $article->title . '  ' . $article->comment_count; 
  11.     echo "<br />"; 
  12.   } 
  13. }

Tags: Laravel5.1模型查询 Laravel作用域

分享到: