use core\query\DB;
说明
DB::table('表名','连接名','数据库名')
PS: 连接名非必填,默认数据库在 database.php 的 database 中配置
PS: 数据库名非必填,默认数据库在 database.php 的 database 中配置 : dbname
数量查询
$where = [];
$where['type'] = 1;
$result = DB::table('表名')->where($where)->count();//返回数量
单条查询
$result = DB::table('表名')->find();
调试模式
$where = [];
$result = DB::table('表名')->where($where)->debug()->find(); //返回sql
join连表查询
$where = [];
$result = DB::table('表名1')
->alias('a')
->join('表名2 b','a.id = b.docid','left')
->where($where)
->find();//两表查询
$join = [
['表名2 b','a.id = b.docid','left'],
['表名3 c','b.docid = c.apiid','left'],
];
$result = DB::table('表名1')->alias('a')->join($join)->find(); //三表查询
union查询
$union = array(
'select * from 表1',
'select * from 表2',
);
$result = DB::table('表3')->alias('a')->union($union)->find(); //多表联合
多条查询
$where = array();
$where['sex'] = 1;
$order = array();
$order['id'] = 'desc';
$order['sex'] = 'asc';
$limit = [0,10];
$group = ['id','sex'];
$result = DB::table('表名')->where($where)->order($order)->group($group)->limit($limit)->select();
插入数据
$data = array();
$data['name'] = 'update33233';
$data['sex'] = 1;
$result = DB::table('表名')->insert($data); //单条插入(一维数组)
$data = array();
$data = [
[
'name' => 'update33233',
'sex' => 1,
],
[
'name' => 'update1111',
'sex' => 2,
],
];
$result = DB::table('表名')->insert($data); //批量多条插入(二维数组)
更新及事务
$data = array();
$data['name'] = 'update222';
$data['sex'] = 1;
$data['id'] = 42;
$bbb = array();
$bbb[] = $data;
DB::Transaction();//开启事务
$result = DB::table('表名')->update($bbb);
if($result)
{
DB::Commit();
}else{
DB::Rollback();
}
删除
$result = DB::table('表名')->delete(主键id); //根据主键id删除
$where = [];
$where['id'] = 1;
$result = DB::table('表名')->where($where)->delete(); //根据条件删除