tp5-5 连接,操作,调试数据库
0
无    2018-04-10 20:31:06    5593    0
fumingwan



使用动态连接& 模型类定义

 当模型操作的时候会自动连接给定的数据库连接,而不是配置文件中设置的默认连接信息

1 在 应用配置文件config.php  里添加数组配置

 

<?
    'machine'=> [
            // 数据库类型
            'type'        => 'mysql',
            // 服务器地址
            'hostname'    => '127.0.0.1',
            // 数据库名
            'database'    => 'machine',
            // 数据库用户名
            'username'    => 'root',
            // 数据库密码
            'password'    => 'root',
            // 数据库编码默认采用utf8
            'charset'     => 'utf8',
            // 数据库表前缀
            'prefix'      => '',
        ],
    'rbac'=>'mysql://root:root@localhost:3306/rbac#utf8',

 

2 动态连接:在方法里应用

 

<?
$machine = Db::connect('machine')->query('select * from admin_users where id=1');

$rbac = Db::connect('rbac')->query('select * from role where id=1');

3 模型类定义:在模型里应用

<?php
namespace app\admin\model;

use think\Model;
use think\Db;
 
class Access extends Model
{
	protected $connection = [
            // 数据库类型
            'type'        => 'mysql',
            // 服务器地址
            'hostname'    => '127.0.0.1',
            // 数据库名
            'database'    => 'rbac',
            // 数据库用户名
            'username'    => 'root',
            // 数据库密码
            'password'    => 'root',
            // 数据库编码默认采用utf8
            'charset'     => 'utf8',
            // 数据库表前缀
            'prefix'      => '',
        ];
    
}

4 在方法里使用此模型类

<?
	public function useMode()
	{
		$a = new Access;
		dump($a::all());
		dump($a->query('select * from role where id=1'));
		
		$res = $a->table('access')->where('id','1')->find();
		dump($res);

	}

 

1 使用数据表前缀和未使用的区别

未使用前缀 直接table 里写表名

<?
use think\Db;
查询一条数据使用:
// table方法必须指定完整的数据表名
Db::table('think_user')->where('id',1)->find();
find 方法查询结果不存在,返回 null

查询数据集使用:
Db::table('think_user')->where('status',1)->select();
select 方法查询结果不存在,返回空数组

使用了前缀的话 name会拼接  参数 数据库表前缀  'prefix' => 'think_',  组成一个table名字

<?
Db::name('user')->where('id',1)->find();
Db::name('user')->where('status',1)->select();

 

2 打印sql 语句

<?
//-------------------------------
// 第一种                       |
//-------------------------------
dump(Db::getLastSql());

//-------------------------------
// 第二种添加 ->fetchSql()      |
//-------------------------------
$data = Db::table('user')->fetchSql()->where($map)->select(); 

 

3 操作sql 语句 1 

execute 操作增删改 返回的均是影响行数

 


a 增

<?
public function insert()
{
	$res = Db::execute("insert into user(username,password) values('小黄','12345')");
	$res = Db::execute("insert into user(username,password) values(:name,:pa)",['name'=>'大礼','pa'=>'666']);
	dump($res);
}

 

b 删

 

<?
public function delete()
{
   $res = Db::execute('delete from user where id >:id',['id'=>6]);
   dump($res);
}

 

 

c 改

 

<?
public function update()
{
	$res = Db::execute('update user set username=:name where id >=:id',['id'=>5,'name'=>'史泰龙']);
    dump($res);
}

 

 

d 查

<?
think\Db;
//使用占位符
$result = Db::query('select * from think_user where id>? and id<?',[0,3]);

$result = Db::query('select * from user where id>:id1 and id<=:id2',['id1'=>0,'id2'=>3]);

 

 

4 使用查询构造器

Db类 是单例模式  db助手函数则不是每次使用将重复链接数据库

->find()是一条数据

->select()是数据集合

查询

1 查询集合和单一数据

   数组查询

    等于

    大于等于(注意同字段加条件要另起一个where( ))

    like模糊查询

    whereOr 或者

   limit 2

   limit 2,3 

   order 排序

   设置 查询字段 和 起别名

          使用count sum 函数 尽量用 find( )

          field第二参数true   排除字段

  column 代替select 和find

  page 分页

  group 和  having 分组聚合的条件选

  join  可放数组里

  DISTINCT 方法用于返回唯一不同的值 

  cache 缓存有效期是由默认的缓存配置参数决定的,但cache方法可以单独指定

 fetchSql用于直接返回SQL而不是执行查询

<?php
use think\Db;
$map['id']  = ['>',1];
$map['username'] = ['like','%u%'];
$map['status'] = 0;
// 把查询条件传入查询方法
$data = Db::table('user')->where($map)->select(); 


$data = Db::table('user')->where('id','10')->select();

// 也可以使用助手函数
$data = db('user')->where('id','10')->select();
$data = db('user')->where('id','>=','4')->where('id','<','9')->select();
$data = db('user')->where('username','like','%u%')->where('id','<','6')->select();
$data = db('user')->where('id','>=','6')->whereOr('id','<=','2')->select();
$data fetchSql= db('user')->where('id','>=','6')->whereOr('id','<=','2')->limit(2)->select();
$data = db('user')->where('id','>=','6')->whereOr('id','<=','1')->limit(2,3)->select();
$data = db('user')->where('id','>=','1')->whereOr('id','<=','1')->limit(2,6)->order('id','desc')->select();
$data = db('user')->field('username nameis,count(*) as cou')->where('id','>=','1')->whereOr('id','<=','1')->limit(2,6)->order('id','desc')->select();
$data = db('user')->field('count(*) as cou')->where('id','>=','1')->whereOr('id','<=','1')->limit(2,6)->order('id','desc')->find();
$data = db('user')->field('username,password',true)->select();

//下面 column一个值是二维,两个值时首个做键二维,三个值首个值做键,三维
$data = db('user')->where('username','like','%u%')->column('username,password,status');
/** page 分页
 *  page(1,5)  第一页:第一条到第五条
 *  page(2,5)  第二页:第六条到第十条
 */
$data = db('user')->page('2,5')->select();
//group 分组  和 having 分组聚合后的选择
$data = Db::table('user')->field('status,count(*) as co')->group('status')->select();
$data = Db::table('user')->field('status,count(*) as co')->group('status')->having('co > 2')->select();

//join
$data = Db::table('user')->alias('u')
  ->where('u.id=:iidd',['iidd'=>1])
  ->field('u.username,ur.role_id,r.name')
  ->join('user_role ur','ur.uid=u.id')
  ->join('role r','r.id=ur.role_id')
  ->select();
  
// DISTINCT 方法用于返回唯一不同的值 
Db::table('user')->distinct(true)->field('username')->select();
//缓存
$data = Db::table('user')->where('id','10')->cache(true)->select();
$data = Db::table('user')->where('id','10')->cache(60)->select();  //缓存60秒

// cache方法可以指定缓存标识:
$data = Db::table('user')->cache('key',60)->find();
$data = \think\Cache::get('key');

//fetch
$data = Db::table('user')->fetchSql(true)->find(1);
输出result结果为: SELECT * FROM think_user where id = 1



 

新增

1 使用返回自增主键函数getLastInsID() 必须要跟插入数据函数insert($data);一起执行

2 或者使用  insertGetId 代替 getLastInsID() 和insert  直接返回主键

 

<strong><?php
$data = [
      'username'=>'张华',
      'password'=>'5555'
        ];
$resutl = Db::table('user')->insert($data);
//返回自增主键  
$userId = Db::name('user')->getLastInsID();
//也可以直接自增返回
$resutl = Db::table('user')->insertGetId($data);

//一次插入多条数据
$data = [
            [ 'username'=>'李二','password'=>'5555'],
            [ 'username'=>'王大','password'=>'5555'],
        ];
$resutl = Db::table('user')->insertAll($data);
 </strong>

 

更新

<?php
$data = [
            'username'=>'二狗','password'=>'erere',
         ];
$resutl = Db::table('user')->where('id', 2)->update($data);

删除p;\

 

<?php
//根据主键删除
$result = Db::table('user')->delete([12,13,14]);
//根据条件删除
$result = Db::table("user")->where('password','=','1111111')->delete();

 

 

聚合函数

1 count( ) 统计

2 max( ) 最大值

3 min( ) 最小值

4 avg( ) 平均值

5 sum( ) 求和

<?php
$result = Db::table('user')->where('status','=','0')->count();

$result = Db::table('user')->where('status','=','0')->avg('id');

 

 时间表达式

<?php
使用whereTime方法
whereTime方法提供了日期和时间字段的快捷查询,示例如下:

// 大于某个时间
Db::table('think_user')->whereTime('birthday', '>=', '1970-10-1')->select();
// 小于某个时间
Db::table('think_user')->whereTime('birthday', '<', '2000-10-1')->select();
// 时间区间查询
Db::table('think_user')->whereTime('birthday', 'between', ['1970-10-1', '2000-10-1'])->select();
// 不在某个时间区间
Db::table('think_user')->whereTime('birthday', 'not between', ['1970-10-1', '2000-10-1'])->select();
时间表达式
还提供了更方便的时间表达式查询,例如:

// 获取今天的博客
Db::table('think_blog') ->whereTime('create_time', 'today')->select();
// 获取昨天的博客
Db::table('think_blog')->whereTime('create_time', 'yesterday')->select();
// 获取本周的博客
Db::table('think_blog')->whereTime('create_time', 'week')->select();   
// 获取上周的博客
Db::table('think_blog')->whereTime('create_time', 'last week')->select();    
// 获取本月的博客
Db::table('think_blog')->whereTime('create_time', 'month')->select();   
// 获取上月的博客
Db::table('think_blog')->whereTime('create_time', 'last month')->select();      
// 获取今年的博客
Db::table('think_blog')->whereTime('create_time', 'year')->select();    
// 获取去年的博客
Db::table('think_blog')->whereTime('create_time', 'last year')->select();     
如果查询当天、本周、本月和今年的时间,还可以简化为:

// 获取今天的博客
Db::table('think_blog')->whereTime('create_time', 'd')->select();
// 获取本周的博客
Db::table('think_blog')->whereTime('create_time', 'w')->select();   
// 获取本月的博客
Db::table('think_blog')->whereTime('create_time', 'm')->select();   
// 获取今年的博客
Db::table('think_blog')->whereTime('create_time', 'y') ->select();    
V5.0.5+版本开始,还可以使用下面的方式进行时间查询

// 查询两个小时内的博客
Db::table('think_blog')->whereTime('create_time','-2 hours')->select();

 闭包查询

 

<strong><?php
$id = input($id);
$result = Db::table('banner_item')
        ->where(function($query) use ($id){
            $query->where('banner_id','=',$id);
        })
        ->select();</strong>

 

 5 事务机制

mysql事务 必须要求数据库是 innodb 引擎

 自动控制事务

<?php
use think\Db;
// 启动事务
        Db::startTrans();
        try{
            $a = Db::table('user')->delete(29);
            if(!$a)throw new \Exception('删除没成功');
            
           
           $b = Db::table('user')->delete(90);
            
            if(!$b)throw new \Exception('插入没成功');
            // 提交事务
            Db::commit();
            echo '完成';
            
        } catch (\Exception $e) {
            echo $e->getMessage();
            // 回滚事务
            Db::rollback();
        }
//更简洁
        Db::startTrans();
        $a = Db::table('user')->delete(26);
        $b = Db::table('user')->delete(90);
         if($a && $b)
        {
            Db::commit();
        }
        else
        {
            Db::rollback();
        }
        echo '完成';

 调试数据库

 

application/database.php 开启调试

// 数据库调试模式
    'debug'           => true,

 application/config.php   开启  日志

 
// 开启日志
    'log'                    => [
        // 日志记录方式,内置 file socket 支持扩展
        'type'  => 'file',//正常File是开启的  test是关闭
        // 日志保存目录
        'path'  => LOG_PATH,
        // 日志记录级别
        'level' => ['sql'],
    ],

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

1.0】快捷键和模板
文档导航