一、数据库连接配置
-
本地测试
直接在.env中修改,不用去config/database.php中修改

正式环境,在部署环境下数据库连接在 config 目录下的 database.php 文件中进行配置:

二、静态方式访问数据库
在tp6 中可以使用 Db 访问数据库,例如:
php
<?php
namespace app\controller;
use app\BaseController;
use think\facade\Db;
class Index extends BaseController
{
public function index()
{
$stu = Db::table('hkcms_auth_rule')->select();
return json($stu);
}
}
以上代码中 use 了 use think\facade\Db; 随后在 index 方法中 使用 Db 指定数据表对其进行 select 操作,最后结果如下:

三、多个数据库操作
此时我们还有一个数据库数据需要获取,那么如何连接其他数据库呢?假设有一数据库如下:



四、使用模型对数据库进行操作
在 tp6 中,框架制定了一个模型类让我们对其使用,通过模型类可以减少重复的代码,并且更加简洁的对数据库进行操作,使用模型对数据库表进行操作时,这个模型即代表了所需要操作的数据库表。
首先在 controller 同级目录下创建一个 model 文件夹,在其中创建对应数据库的模型文件:

三、增删改查
新增的控制器路径为 app\controller\CURD.php

- 引入Db库
php
use think\facade\Db;
查
php
<?php
namespace app\controller;
use app\BaseController;
use think\facade\Db;
class CURD extends BaseController
{
public function select()
{
// 查所有
$result = Db::name('hkcms_admin')->select()->toArray();
print_r($result);
print_r('<br/>');
print_r('<br/>');
// 查一个 (多个条件用多个where)
$result = Db::name('hkcms_admin')->where('username', 'admin')
->where('id', '>', 0)->select()->toArray();
var_dump($result);
}
}
-
查询使用select(),返回的是对象,所以要用->toArray()转成数组
-
查询条件使用where('字段名','查询表达式','查询条件'),缺省'查询表达式'表示等于
-
多个where可以连接
