Laravel5.1 数据库-查询构建器
今儿个咱说说查询构建器。它比运行原生SQL要简单些,它的操作面儿也是比较广泛的。
1 查询结果
先来看看它的语法:
public function getSelect()
{
$result = DB::table('articles')->get();
dd($result);
}
查询构建器就是通过table方法返回的,使用get()可以返回一个结果集(array类型) 这里是返回所有的数据,当然你也可以链接很多约束。
1.1 获取一列/一行数据
public function getSelect()
{
$result = DB::table('articles')->where('title', 'learn database')->get(); // 获取整列数据
$articles = DB::table('articles')->where('title', 'learn database')->first(); // 获取一行数据
dd($result, $articles);
}
我们可以通过where来增添条件。
1.2 获取数据列值列表
如果你想要取到某列的值的话 可以使用lists方法:
public function getSelect()
{
$result = DB::table('articles')->where('id', '<', 2)->lists('title');
$titles = DB::table('articles')->lists('title');
dd($result, $titles);
}
1.3 获取组块儿结果集
在我们数据表中数据特别特别多时 可以使用组块结果集 就是一次获取一小块数据进行处理
public function getSelect()
{
DB::table('articles')->chunk(2, function ($articles){
foreach ($articles as $article){
echo $article->title;
echo "<br />";
}
});
}
如果说要终止组块运行的话 返回false就可以了:
public function getSelect()
{
DB::table('articles')->chunk(2, function ($articles){
return false;
});
}
1.4 聚合函数
构建器还提供了很多的实用方法供我们使用:
- count方法:返回构建器查询到的数据量。
- max方法:传入一列 返回这一列中最大的值。
- min方法:跟max方法类似,它返回最小的值。
- sum方法:返回一列值相加的和。
- avg方法:计算平均值。
1.4.1 count
public function getArticlesInfo()
{
$article_count = DB::table('articles')->count();
dd($article_count);
}
1.4.2 max
public function getArticlesInfo()
{
$maxCommentCount = DB::table('articles')->max('comment_count');
dd($maxCommentCount);
}
1.4.3 sum
public function getArticlesInfo()
{
$commentSum = DB::table('articles')->sum('comment_count');
}
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(); // 类似
}
2.2 orWhere
orWhere和where接收的参数是一样的,当where逻辑没有查找到 or查找到了 返回or的结果,当where查找到了 or也查找到了 返回它们的结果。
public function getArticlesInfo()
{
$articles = DB::table("articles")->where('id','=','5')->orWhere('title','laravel database')->get();
dd($articles);
}
2.3 whereBetween和whereNotBetween
whereBetween是指列值是否在所给定的值之间:
public function getArticlesInfo()
{
$articles = DB::table("articles")->whereBetween('id', [1, 3])->get();
dd($articles);
}
↑ 上述代码是查找id在1~3之间的集合。
whereNotBetween和whereBetween相反:
public function getArticlesInfo()
{
$articles = DB::table("articles")->whereNotBetween('id', [1, 3])->get();
dd($articles);
}
↑ 上述代码是查找id不在1~3之间的集合。
2.4 whereIn和whereNotIn
whereIn是查找列值在给定的一组数据中:
public function getArticlesInfo()
{
$articles = DB::table("articles")->whereIn('id', [1, 3, 5, 8])->get();
dd($articles);
}
↑ 上述代码中是查找ID为1,3,5,8的集合,不过我们数据库中只有id为1和3的数据 那么它只会返回id为1和3的集合。
whereNotIn和whereIn相反的:
public function getArticlesInfo()
{
$articles = DB::table("articles")->whereNotIn('id', [1, 3, 5, 8])->get();
dd($articles);
}
↑ 上述代码中是查找ID不是1,3,5,8的集合。
2.5 whereNull和whereNotNull
whereNull是查找列值为空的数据:
public function getArticlesInfo()
{
$articles = DB::table("articles")->whereNull('created_at')->get();
dd($articles);
}
↑ 上述代码中是查找created_at为空的集合。
whereNotNull就不用说啦:
public function getArticlesInfo()
{
$articles = DB::table("articles")->whereNotNull('created_at')->get();
dd($articles);
}
↑ 上述代码中是查找created_at不为空的集合。
3 插入数据
先看下最简单的插入方法:
public function getInsertArticle()
{
// 插入一条数据:
DB::table('articles')->insert(
['title'=>'get more', 'body'=>'emmmmmm......']
); // 插入多条数据:
DB::table('articles')->insert([
['title'=>'testTitle1', 'body'=>'testBody1'],
['title'=>'testTitle2', 'body'=>'testBody2'],
// ....
]);
}
当你需要拿到插入数据的ID的话,可以使用获取自增ID的方法:
public function getInsertArticle()
{
// 插入一条数据:
$id = DB::table('articles')->insertGetId(
['title'=>'get more', 'body'=>'emmmmmm......']
); dd($id);
}
4 更新
public function getUpdateArticle()
{
$result = DB::table('articles')->whereBetween('id', [1, 3])->update(['comment_count'=>0]);
dd($result);
}
↑ update还可以返回影响了几条数据。
4.1 加/减快捷方法
public function getUpdateArticle()
{
$result = DB::table('articles')->whereBetween('id', [1, 3])->increment('comment_count',2);
dd($result);
}
↑ increment接受1~2个参数,第一个参数是列名,第二个参数是可选的表示增加几(默认是1),上面的语句是:comment_count这一列的值增加2。
public function getUpdateArticle()
{
$result = DB::table('articles')->whereBetween('id', [1, 3])->decrement('comment_count',2);
dd($result);
}
↑ decrement接受1~2个参数,第一个参数是列名,第二个参数是可选的表示减少几(默认是1),上面的语句是:comment_count这一列的值减少2。
你以为加减快捷方法只接收两个参数么?nonono 它还可以接收第三个参数:
public function getUpdateArticle()
{
$result = DB::table('articles')->whereBetween('id', [1, 3])->increment('comment_count', 2, ['title' => 'testUpdate']);
dd($result);
}
↑ 它还可以在增加/减少时对其他列进行修改。
5 删除
public function getDeleteArticle()
{
$result = DB::table('articles')->whereBetween('id', [1, 3])->delete();
dd($result);
}
↑ 用delete删除数据,它也返回有多少行被影响。
当你想要删除所有的列 并且把自增ID归0的话 可以这么做:
public function getDeleteArticle()
{
DB::table('articles')->truncate();
}
6 锁
查询构建器还包含一些方法帮助你在select语句中实现”悲观锁“。可以在查询中使用sharedLock
方法从而在运行语句时带一把”共享锁“。共享锁可以避免被选择的行被修改直到事务提交:
DB::table('articles')->where('id', '>', 100)->sharedLock()->get();
此外你还可以使用lockForUpdate
方法。”for update“锁避免选择行被其它共享锁修改或删除:
DB::table('articles')->where('id', '>', 100)->lockForUpdate()->get();
Laravel5.1 数据库-查询构建器的更多相关文章
- laravel5.6操作数据curd写法(查询构建器)
laravel5.6 数据库操作-查询构建器 <?php //laravel5.6 语法 demo示例 namespace App\Http\Controllers;//命名该控制App空间下名 ...
- [转]Laravel 数据库实例教程 —— 使用查询构建器实现对数据库的高级查询
本文转自:https://laravelacademy.org/post/920.html 上一节我们简单介绍了如何使用查询构建器对数据库进行基本的增删改查操作,这一节我们来探讨如何使用查询构建器实现 ...
- Laravel 数据库实例教程 —— 使用查询构建器对数据库进行增删改查
原文地址:https://blog.csdn.net/lmy_love_/article/details/72832259 获取查询构建器很简单,还是要依赖DB门面,我们使用DB门面的table方法, ...
- Yii2 查询构建器 QueryBuilder
查询构造器 QueryBuilder 1.什么是查询构建器 查询构建器也是建立在 DAO 基础之上,可让你创建程序化的.DBMS 无关的 sql 语句,并且这样创建的 sql 语句比原生的 sql 语 ...
- DB门面,查询构建器,Eloquent ORM三者的CURD
一.DB门面 1.insert DB::insert('insert into table(`name`) value(?)', ['test']); 2.update DB::update('upd ...
- laravel 查询构建器(连贯操作)
注:laravel 查询返回行的都是 php 的 stdClass 对象实例,不是数组!!!! 1)查询多行(get) DB::table('table_name')->get(); 带偏移和限 ...
- 定义查询构建器IFeatureLayerDefinition
在宗地出图,需要实现,只显示某一户人的地块.在ArcMap里,有个定义查询,可只显示过滤后的要素. 在代码中,也比较好实现,使用IFeatureLayerDefinition接口即可. IFeatur ...
- yii2 查询构建器
Query Builder $rows = (new \yii\db\Query()) ->select(['dyn_id', 'dyn_name']) ->from('zs_dynast ...
- Yii2将查询数据变为键值对数组及查询构建器
随机推荐
- shareToQQ,qq 4.1.1 for android,闪退
用shareToQQ函数分享图文消息,在qq 4.1.1 for android版本下打开联系人列表数秒后会闪退!在更高版本的V4.5.2.1,V4.2.1下则没有这个问题(证明各种设置没问题),各位 ...
- TestNG+ReportNG+Maven优化测试报告
转载:https://www.cnblogs.com/hardy-test/p/5354733.html 首先在eclipse里面创建一个maven项目,具体要配置maven环境,请自行百度搭配环境. ...
- Linux学习笔记 (八)Shell概述
一.什么是Shell? Shell是一个命令行解释器,它为用户提供了一个向Linux内核发送请求以便运行程序的界面系统级程序,用户可以用Shell来启动,挂起,停止甚至是编写一些程序.Shell还是一 ...
- formidable 模块化开发 代码拆分(解耦) nodejs图片服务器架构
引言:程序要做到:健壮性.低耦合.可扩展.方便程序员分工合作 上传图片值nodejs服务器并显示图片的源代码: post.html : <!DOCTYPE html> <html l ...
- js apply和call区别
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8&quo ...
- JavaScript完整性检查
1.7个“坑” <!DOCTYPE html> <html lang="zh"> <head> <meta charset="U ...
- docker发布spring cloud应用
原文地址:http://www.cnblogs.com/skyblog/p/5163691.html 本文涉及到的项目: cloud-simple-docker:一个简单的spring boot应用 ...
- LA 5009 (HDU 3714) Error Curves (三分)
Error Curves Time Limit:3000MS Memory Limit:0KB 64bit IO Format:%lld & %llu SubmitStatusPr ...
- Redis之ZSet命令
0.前言 Redis有序集合ZSet可以按分数进行排序, 存储结构可能使用ziplist,skiplist和hash表, zset_max_ziplist_entries和zset_max_zipli ...
- C# 泛型方法
泛型方法是使用类型参数声明的方法,如下所示: static void Swap<T>(ref T lhs, ref T rhs) { T temp; temp = lhs; lhs = r ...