ThinkPHP6 数据库和模型操作已经独立为ThinkORM库
要使用Db类必须使用门面方式( think\facade\Db )调用
数据库操作统一入口: Db::
修改数据库配置
根目录的env
config目录database.php(若需多个数据库再新增connections)
connect 方法动态配置数据库连接信息
Db::connect('database2')->table('shop_user')->select();
执行原生 MySql
1、query 方法用于执行 MySql 查询操作
public function index(){
$query = Db::query("SELECT * FROM `shop_goods` where status=1");
print_r($query);
}
2、execute 方法用于执行 MySql 新增和修改操作
public function index(){
$execute = Db::execute("INSERT INTO `shop_goods` VALUES (3, 1, '2019秋冬新款时尚简约纯羊绒加厚圆领羊绒长裙显瘦气质连衣裙女', 1179.00, 0, 200, 1, 1576080000)");
print_r($execute);
$execute = Db::execute("UPDATE `shop_goods` set `price`='1100' where `id`=3 ");
print_r($execute);
}
模板读数据库数据(需将对象转换成数组,才能修改)
$title = '商城';
$login = '过开羽';
$left = Db::table('shop_menu')->where('fid',0)->select();
$left = $left->toArray();
foreach ($left as &$left1){
$son = Db::table('shop_menu')->where('fid',$left1['id'])->select();
$left1['lists'] = $son->toArray();
}
$right = Db::table('shop_goods')->select();
$right = $right->toArray();
View::assign([
'title' => $title,
'login' => $login,
'left' => $left,
'right' => $right
]);
return View::fetch();
}
SQL命令速查
选择:select * from table1 where 范围
插入:insert into table1(field1,field2) values(value1,value2)
删除:delete from table1 where 范围
更新:update table1 set field1=value1 where 范围
查找:select * from table1 where field1 like ’%value1%’ —like的语法很精妙,查资料!
排序:select * from table1 order by field1,field2 [desc]
总数:select count as totalcount from table1
求和:select sum(field1) as sumvalue from table1
平均:select avg(field1) as avgvalue from table1
最大:select max(field1) as maxvalue from table1
最小:select min(field1) as minvalue from table1