原生查询和查询构造器

原生查询

Db::execute(要执行的sql语句);

Db::query(要执行的sql语句);

execute方法用于增,删,改,返回值是影响的行数

query方法用于查询,返回的是数据集(二维数组)

查询构造器

db('data')->insert(['id'=>20])
db('data')->where('id',20)->update(['id'=>20])
db('data')->where('id',20)->select()
db('data')->where('id',20)->delete()

db助手函数默认会每次重新链接数据库,避免多次使用

返回sql语句

$res=db('data')->fetchsql()->select()

事务支持

由于需要用到事务的功能,请先修改数据表的类型为InnoDB,而不是MyISAM。
对于事务的支持,最简单的方法就是使用transaction方法,只需要把需要执行的事务操作封装到闭包里面即可自动完成事务,例如:
Db::transaction(function () {   
	Db::table('think_user') ->delete(1);   
	Db::table('think_data') ->insert(['id' => 28, 'name' => 'thinkphp', 'status' => 1]);
 });

手动提交事务

//启动事务
Db::startTrans()
try{
Db::table('data')->delete(2);
Db::commit()
}catch(\Exveption $e){
	Db::rollback()
}

时间查询

首先需要在 think_data 数据表新增 create_time 字段,用于日期查询的字段类型推荐使用
datetime 类型。

// 查询创建时间大于2016-1-1的数据
$result = Db::name('data')
->whereTime('create_time', '>', '2016-1-1')
->select();
dump($result);
// 查询本周添加的数据
$result = Db::name('data')
->whereTime('create_time', '>', 'this week')
->select();
dump($result);
// 查询最近两天添加的数据
$result = Db::name('data')
->whereTime('create_time', '>', '-2 days')
->select();
dump($result);
// 查询创建时间在2016-1-1~2016-7-1的数据
$result = Db::name('data')
->whereTime('create_time', 'between', ['2016-1-1', '2016-7-1'])
->select();
dump($result);
还可以使用下面的人性化日期查询方式,例如:
// 获取今天的数据
$result = Db::name('data')
->whereTime('create_time', 'today')
->select();
dump($result);
// 获取昨天的数据
$result = Db::name('data')
->whereTime('create_time', 'yesterday')
->select();
dump($result);
// 获取本周的数据
$result = Db::name('data')
->whereTime('create_time', 'week')
->select();
dump($result);
// 获取上周的数据
$result = Db::name('data')
->whereTime('create_time', 'last week')
->select();
dump($result);

分块查询

(例如查询所有的数据并导出到 excel ),采用
分块查询可以缓解这个问题。

使用分块查询,可以把1万条记录分成 100 次处理,每次处理 100 条记录,代码示例如下:
Db::name('data')
->where('status', '>', 0)
->chunk(100, function ($list) {
// 处理100条记录
foreach($list as $data){
}
});

第二个参数可以是有效的 callback 类型,包括使用闭包函数。
系统会按照主键顺序查询,每次查询 100 条,如果你不希望使用主键进行查询,或者没有主键的话,则需要
指定查询的排序字段(但必须是唯一的),例如:
Db::name('user')
->where('status', '>', 0)
->chunk(100, function ($list) {
// 处理100条记录
foreach($list as $data){
}
}, 'uid');
然后交给 callback 进行数据处理,处理完毕后继续查询下一个 100 条记录,如果你需要在中途中断后续
的查询,只需要在 callback 方法调用中返回 false 即可,例如:
Db::name('data')
->where('status','>',0)
->chunk(100,function($list){
foreach($list as $data){
// 返回false则中断后续查询
return false;
}
});



聚合查询

count max min avg sum

$count=db('data')->where('status',1)->count()

查询指定字段

$name=Db::name('data')->where('id','=','8')->value('name');
posted @ 2020-08-04 13:45  琴似蓝调  阅读(330)  评论(0编辑  收藏  举报