Laravel5.1 框架数据库查询构建器用法实例详解(2)
1.4.4 avg
public function getArticlesInfo()
{
$commentAvg = DB::table('articles')->avg('comment_count');
dd($commentAvg);
}
1.5 select查询
1.5.1 自定义子句
select语句可以获取指定的列,并且可以自定义键:
public function getArticlesInfo()
{
$articles = DB::table('articles')->select('title')->get();
// 输出结果:
// array:3 [▼
// 0 => {#150 ▼
// +"title": "laravel database"
// }
// 1 => {#151 ▼
// +"title": "learn database"
// }
// 2 => {#152 ▼
// +"title": "alex"
// }
// ]
$articles1 = DB::table('articles')->select('title as articles_title')->get();
// 输出结果:
// array:3 [▼
// 0 => {#153 ▼
// +"articles_title": "laravel database"
// }
// 1 => {#154 ▼
// +"articles_title": "learn database"
// }
// 2 => {#155 ▼
// +"articles_title": "alex"
// }
// ]
$articles2 = DB::table('articles')->select('title as articles_title', 'id as articles_id')->get();
// array:3 [▼
// 0 => {#156 ▼
// +"articles_title": "laravel database"
// +"articles_id": 1
// }
// 1 => {#157 ▼
// +"articles_title": "learn database"
// +"articles_id": 2
// }
// 2 => {#158 ▼
// +"articles_title": "alex"
// +"articles_id": 3
// }
// ]
}
1.5.2 distinct方法
关于distinct方法我还没弄明白到底是什么意思 适用于什么场景,也欢迎大神们给出个答案 谢谢
distinct方法允许你强制查询返回不重复的结果集。
public function getArticlesInfo()
{
$articles = DB::table('articles')->distinct()->get();
}
1.5.3 addSelect方法
如果你想要添加一个select 可以这样做:
public function getArticlesInfo()
{
$query = DB::table('articles')->select('title as articles_title');
$articles = $query->addSelect('id')->get();
dd($articles);
}
2 where语句
where语句是比较常用的,经常用他来进行条件筛选。
2.1 where基础介绍
现在来详细介绍下where方法 它接收三个参数:
- 列名,这个没什么好说的。
- 数据库系统支持的操作符,比如说 ”=“、”<“、”like“这些,如果不传入第二个参数 那么默认就是”=“等于。
- 要比较的值。
public function getArticlesInfo()
{
$articles1 = DB::table('articles')->where('id','2')->get(); // 等于
$articles2 = DB::table('articles')->where('id','>','2')->get(); // 大于
$articles3 = DB::table('articles')->where('id','<>','2')->get(); // 不等于
$articles4 = DB::table('articles')->where('id','<=','2')->get(); // 小于等于
$articles5 = DB::table('articles')->where('title','LIKE','%base')->get(); // 类似
}
内容版权声明:除非注明,否则皆为本站原创文章。
