新增更新都是save、saveAll  怎么识别他们

  • 实例化模型后调用save方法表示新增;
  • 查询数据后调用save方法表示更新;
  • save方法传入更新条件后表示更新;

isUpdate(true):强制更新

isUpdate(false):强制新增

新建模型

1、手动创建

    1. app的模块文件夹下新建model文件夹
    2. 新建文件user.php。最好名字和表名对应
    3. 写代码
<?php
namespace app\admin\model;
use think\Model;
class User extends Model
{
//如果表名和文件名不是对应的,用下面代码修改
protected $table = 'think_user';
}

2、用命令

>php think make:model admin/Blog

模型实例化

1、用静态方法

use app\admin\model\User;
$li= User::get(1);

2、用加载类(单例)  

use think\Loader;
$user= Loader::model('User');
//某些路由可能导致获取不到模块哦(如这条路由别名Route::alias('showindex','\app\test\controller\Index');),所以尽量将参数多加个模块或者直接类全名
$user= Loader::model('admin/user');
$user= Loader::model('app\admin\model\User');
$li= $user::get(1);

3、用系统方法相当于D()封装的(Loader::model()

$user= model('User');
$li= $user::get(1);

4、实例化模型

use app\admin\model\User;
$user = new User;
$user->name= 'thinkphp';
$user->save();

获取单条数据

//直接实例化model类
$user = new User();
$user->where('name', 'thinkphp')->find();
或者
//取出主键为1的数据
$user = User::get(1);
echo $user->name; // 使用数组查询
$user = User::get(['name' => 'thinkphp']); // 使用闭包查询
$user = User::get(function($query){
$query->where('name', 'thinkphp');
});
echo $user->name;//如果你是在模型内部,请不要使用$this->name的方式来获取数据,请使用$this->getAttr('name') 替代

获取多个数据(5.0.4+支持在模型中设置resultSetType返回数据集对象的名称)

$user = new User();
// 查询数据集
$user->where('name', 'thinkphp')
->limit(10)
->order('id', 'desc')
->select();
或者 // 根据主键获取多个数据
$list = User::all('1,2,3');
// 或者使用数组
$list = User::all([1,2,3]);
foreach($list as $key=>$user){
echo $user->name;
}
// 使用数组查询
$list = User::all(['status'=>1]);
// 使用闭包查询
$list = User::all(function($query){
$query->where('status', 1)->limit(3)->order('id', 'asc');
});
foreach($list as $key=>$user){
echo $user->name;
}

获取某个字段或者某个列的值

// 获取某个用户的积分(某个字段的值单个值)
User::where('id',10)->value('score');
// 获取某个列的所有值(多个值)
User::where('status',1)->column('name');
// 以id为索引
User::where('status',1)->column('name','id');
User::where('status',1)->column('id,name'); // 同tp3的getField

添加一条数据save

$user           = new User;
$user->name = 'thinkphp';
$user->email = 'thinkphp@qq.com';
$user->save(); 或者 $user = new User;
$user->data([
'name' => 'thinkphp',
'email' => 'thinkphp@qq.com'
]);
$user->save(); 又或者
$user = new User([
'name' => 'thinkphp',
'email' => 'thinkphp@qq.com'
]);
$user->save(); 如果需要过滤非数据表字段的数据,可以使用: $user = new User($_POST);
// 过滤post数组中的非数据表字段数据
$user->allowField(true)->save();
如果你通过外部提交赋值给模型,并且希望指定某些字段写入,可以使用: $user = new User($_POST);
// post数组中只有name和email字段会写入
$user->allowField(['name','email'])->save();

获取自增id

$user           = new User;
$user->name = 'thinkphp';
$user->email = 'thinkphp@qq.com';
$user->save();
// 获取自增ID 与表中的id名对应
echo $user->user_id;

注意不要在同一个实例里面多次新增数据,如果确实需要多次新增,那么可以用下面的方式

$user           = new User;
$user->name = 'thinkphp';
$user->email = 'thinkphp@qq.com';
$user->save();
$user->name = 'onethink';
$user->email = 'onethink@qq.com';
// 第二次开始必须使用下面的方式新增
$user->isUpdate(false)->save();

新增多条数据saveAll

$user = new User;
$list = [
['name'=>'thinkphp','email'=>'thinkphp@qq.com'],
['name'=>'onethink','email'=>'onethink@qq.com']
];
$user->saveAll($list);
//saveAll方法新增数据返回的是包含新增模型(带自增ID)的数据集(数组)。V5.0.13+版本开始,saveAll方法的返回类型受模型的resultSetType属性影响(可能返回数据集对象) aveAll方法新增数据默认会自动识别数据是需要新增还是更新操作,当数据中存在主键的时候会认为是更新操作,如果你需要带主键数据批量新增,可以使用下面的方式:
$user = new User;
$list = [
['id'=>1, 'name'=>'thinkphp', 'email'=>'thinkphp@qq.com'],
['id'=>2, 'name'=>'onethink', 'email'=>'onethink@qq.com'],
];
$user->saveAll($list, false);

助手函数

// 使用model助手函数实例化User模型
$user = model('User');
// 模型对象赋值
$user->data([
'name' => 'thinkphp',
'email' => 'thinkphp@qq.com'
]);
$user->save(); 或者进行批量新增(saveAll):
$user = model('User');
// 批量新增
$list = [
['name'=>'thinkphp','email'=>'thinkphp@qq.com'],
['name'=>'onethink','email'=>'onethink@qq.com']
];
$user->saveAll($list);

静态方法

还可以直接静态调用create方法创建并写入:

$user = User::create([
'name' => 'thinkphp',
'email' => 'thinkphp@qq.com'
]);
echo $user->name;
echo $user->email;
echo $user->id; // 获取自增ID

改  注意新增和更新都是save 有id就更新

先查找在修改 (get和find返回的都是是当前模型的对象实例)

  //更新id为1的数据(先查出id位1的数据,在save更新)
$user = User::get(1);
$user->name = 'thinkphp';
$user->email = 'thinkphp@qq.com';
$user->save();
或者:
$user=new User;// or $user= Loader::model('User'); or $user= model('User');
$data=$user->where('id', '1')->find();
$data->name = 'thinkphp111';
$data->save();

直接更新数据

model('User')->save(array $data,array $where)

$user = new User;
// save方法第二个参数为更新条件
$user->save([
'name' => 'thinkphp',
'email' => 'thinkphp@qq.com'
],['id' => 1]);

过滤非数据表字段的数据allowField(true or 'field')

直接更新post或者get数据需要去掉post/get中不是数据表字段的参数

$user = new User();
// 过滤post数组中的非数据表字段数据
$user->allowField(true)->save($_POST,['id' => 1]);
// post数组中只有name和email字段会写入
$user->allowField(['name','email'])->save($_POST, ['id' => 1]);

闭包更新 (可以调用多个更新条件)

//可以通过闭包函数使用更复杂的更新条件,例如:
$user = new User;
$user->save(['name' => 'thinkphp'],function($query){
// 更新status值为1 并且id大于10的数据
$query->where('status', 1)->where('id', '>', 10);
});

通过数据库类更新数据update()方法(必要时,这个不能无法使用模型的事件功能)

$user = new User;
$user->where('id', 1)->update(['name' => 'thinkphp']);
//如果传入update的数据包含主键的话,可以无需使用where方法。
$user->update(['id' => 1, 'name' => 'thinkphp']);
或者(静态方法)
User::where('id', 1) ->update(['name' => 'thinkphp']);
//如果传入update的数据包含主键的话,可以无需使用where方法。
User::update(['id' => 1, 'name' => 'thinkphp']);

批量更新:saveAll(存在主键的二维数组) 无主键需要foreach循环更新

$user = new User;
$list = [
['id'=>1, 'name'=>'thinkphp', 'email'=>'thinkphp@qq.com'],
['id'=>2, 'name'=>'onethink', 'email'=>'onethink@qq.com']
];
$user->saveAll($list); //5.013+版本可以使用isUpdate()方法对saveAll强制更新(尤其适合于复合主键的情况) save则是5.0+
$user->isUpdate()->saveAll($list);

$user = User::get(1);
$user->delete(); 根据主键删除
User::destroy(1);
// 支持批量删除多个数据
User::destroy('1,2,3');
// 或者
User::destroy([1,2,3]); 条件删除 // 删除状态为0的数据
User::destroy(['status' => 0]);
还支持使用闭包删除,例如: User::destroy(function($query){
$query->where('id','>',10);
});
或者通过数据库类的查询条件删除 User::where('id','>',10)->delete();

Model属性:    // 数据库查询对象池    protected static $links = [];

// 数据库配置
protected $connection = [];
// 父关联模型对象
protected $parent;
// 数据库查询对象
protected $query;
// 当前模型名称(根据模型文件的位置和类名自动生成,查询会查询table属性,table为空时自动拼接表名,name和table属性都出现的话已table为准)
protected $name='user';
// 数据表名称
protected $table='think_user';
注意:name和table都是数据表名只是设置的时候name不用加前缀,而table需要加上前缀 当mode文件的位置不符合规范就用他们
// 当前类名称
protected $class;
// 回调事件
private static $event = [];
// 错误信息
protected $error;
// 字段验证规则
protected $validate;
// 数据表主键 复合主键使用数组定义 不设置则自动获取
protected $pk;
// 数据表字段信息 留空则自动获取
protected $field = [];
// 数据排除字段
protected $except = [];
// 数据废弃字段
protected $disuse = [];
// 只读字段
protected $readonly = [];
// 显示属性
protected $visible = [];
// 隐藏属性
protected $hidden = [];
// 追加属性
protected $append = [];
// 数据信息
protected $data = [];
// 原始数据
protected $origin = [];
// 关联模型
protected $relation = []; // 保存自动完成列表
protected $auto = [];
// 新增自动完成列表
protected $insert = [];
// 更新自动完成列表
protected $update = [];
// 是否需要自动写入时间戳 如果设置为字符串 则表示时间字段的类型
protected $autoWriteTimestamp;
// 创建时间字段
protected $createTime = 'create_time';
// 更新时间字段
protected $updateTime = 'update_time';
// 时间字段取出后的默认时间格式
protected $dateFormat;
// 字段类型或者格式转换
protected $type = [];
// 是否为更新数据
protected $isUpdate = false;
// 是否使用Replace
protected $replace = false;
// 是否强制更新所有数据
protected $force = false;
// 更新条件
protected $updateWhere;
// 验证失败是否抛出异常
protected $failException = false;
// 全局查询范围
protected $useGlobalScope = true;
// 是否采用批量验证
protected $batchValidate = false;
// 查询数据集对象
protected $resultSetType;
// 关联自动写入
protected $relationWrite; /**
* 初始化过的模型.
*
* @var array
*/
protected static $initialized = []; /**
* 是否从主库读取(主从分布式有效)
* @var array
*/
protected static $readMaster;

Model公共方法:

_construct
getQuery(false) 获取当前模型的查询对象
db(true,true) 获取当前模型的数据库查询对象
setParent($model) 设置父关联对象
getParent() 获取父关联对象
data($data,$value=null); 设置数据对象值(即设置model的data属性的值)参数为字符串则追加data,否则就销毁data在赋值
getData($field_name) 获取对象的原始数据(不填参数默认获取全部) 如:$model->find(1)->getData() or $model->select()[0]->getData()返回单条表数据数组
isAutoWriteTimestamp($auto) 动态设置是否需要自动写入时间字段(值为boolean)
force(true) 更新是否强制写入数据 而不做比较
setAttr($name,$value,$data=[]) 修改器 设置数据对象值
getRelation(关联方法名) 获取当前模型的关联模型数据
setRelation($name,$value) 设置关联数据对象值
getAttr($name) 获取器 获取数据对象的值
append(['field_name'=>'value'],false) 设置需要追加的输出属性
appendRelationAttr($relation, $append) 设置附加关联对象的属性
hidden(['field_name1','field_name2',...],false) 设置需要隐藏的输出属性
visible(['field_name1',...],false) 设置需要输出的属性
toArray() 转换当前模型对象为数组
toJson() 转换当前模型对象为JSON字符串
removeRelation($collection) (参数为array|\think\Collection $collection)移除当前模型的关联属性
toCollection() 转换当前模型数据集为数据集对象
together($relation) 关联数据一起更新
getPk($name='') 根据模型名获取模型对象的主键
save($data = [], $where = [], $sequence = null) 新增或修改
getChangedData() 获取变化(即将要修改)的数据 并排除只读数据
setInc($field, $step = 1, $lazyTime = 0) 自增
setDec($field, $step = 1, $lazyTime = 0) 自减
saveAllsaveAll($dataSet, $replace = true) 保存多个数据到当前数据对象
allowField($field) 设置允许写入的字段
except($field) 设置排除写入的字段
readonly($field) 设置只读字段
isUpdate($update = true, $where = null) 是否为更新数据
delete 删除当前的数据
auto($fields) 设置自动完成的字段( 规则通过修改器定义)
validate($rule = true or ruleArr, $msg = [], $batch = false) 设置字段验证
validateFailException(true) 设置验证失败后是否抛出异常
getError() 返回模型的错误信息
::event($event, $callback, $override = false) 注册回调方法
::create 新增
::update 修改
::get 获取单条
::all 获取多条
::destroy 删除
::scope(string|array|\Closure $name) 命名范围
::useGlobalScope($use) 设置是否使用全局查询范围 当为true时即设置useGlobalScapeshu属性为true 当调用model不存在的方法时会直接查找数据库查询类是否存在,存在就调用
::has($relation, $operator = '>=', $count = 1, $id = '*') 根据关联条件查询当前模型
::hasWhere($relation, $where = [], $fields = null) 根据关联条件查询当前模型
relationQuery($relations) 查询当前模型的关联数据
eagerlyResultSet(&$resultSet, $relation) 预载入关联查询 返回数据集
eagerlyResult(&$result, $relation) 关联统计
relationCount
hasOne($model, $foreignKey = '', $localKey = '', $alias = [], $joinType = 'INNER') HAS ONE 关联定义
belongsTo($model, $foreignKey = '', $localKey = '', $alias = [], $joinType = 'INNER') BELONGS TO 关联定义
hasMany($model, $foreignKey = '', $localKey = '') HAS MANY 关联定义
hasManyThrough($model, $through, $foreignKey = '', $throughKey = '', $localKey = '') HAS MANY 远程关联定义
belongsToMany($model, $table = '', $foreignKey = '', $localKey = '') BELONGS TO MANY 关联定义
morphMany($model, $morph = null, $type = '') MORPH  MANY 关联定义
morphOne($model, $morph = null, $type = '') MORPH  One 关联定义
morphTo($morph = null, $alias = []) MORPH TO 关联定义
__call 此函数的作用是调用数据库的方法(当全局查询范围开启时)
__callStatic 作用同上
__set
__get
__isset
__unset
__toString
jsonSerialize()
offsetSet($name,$value)
offsetExists($name)
offsetUnset($name)
offsetGet($name)
__wakeup() 解序列化后处理就一行代码
readMaster(false) 是否从主库读取数据(主从分布有效)
newInstance($data,$isUpdate,$where) 创建新的模型实例
replace($replace = true) 新增数据是否使用Replace
protected (都是model内部方法)
buildQuery() 创建模型的查询对象
initialize() 初始化模型
init() 初始化处理 适合在子类重写
autoWriteTimestamp($name时间戳字段名) 自动写入时间戳
writeTransform($value, $type) 写入数据 类型转换
readTransform($value, $type) 数据读取 类型转换
getRelationData(Relation $modelRelation) 获取关联模型数据
parseAttr($attrs, &$result, $visible = true) 解析隐藏及显示属性
subToArray($model, $visible, $hidden, $key) 转换子模型对象
isPk($key) 判断一个字段名是否为主键字段
checkAllowField($auto = [])
autoRelationUpdate($relation)
getWhere()获取更新条件
autoCompleteData($auto = []) 数据自动完成
validateData($data, $rule = null, $batch = null) 自动验证数据
trigger($event, &$params) 触发事件
::parseQuery(&$data, $with, $cache) 分析查询表达式
parseModel($model) 解析模型的完整命名空间
getForeignKey($name) 获取模型的默认外键名
//模型事件快捷方法
beforeInsert($callback, $override = false)
afterInsert($callback, $override = false)
beforeUpdate($callback, $override = false)
afterUpdate($callback, $override = false)
beforeWrite($callback, $override = false)
afterWrite($callback, $override = false)
beforeDelete($callback, $override = false)
afterDelete($callback, $override = false)

 Model select查出来的数据是数组套对象,我们不能直接使用toArray()方法,而是要遍历出数据在转数组 模型默认的返回类型时array  

数据集:collection

当查询的数据转为数据集后 不管是find还是select查询出来的调用toArray后直接全部转为数组,超级棒 不像array类型还夹杂着对象 

如果是数据集查询的话有两种情况,由于默认的数据集返回结果的类型是一个数组,因此无法调用toArray方法,必须先转成数据集对象然后再使用toArray方法,系统提供了一个collection助手函数实现数据集对象的转换

助手函数collection($data)

        $products=ProductModel::getMostRecent($count);
dump(collection($products)); //注意返回类型为array时才会转换成数据集否则会报错

2当前模型可以定义属性

 protected $resultSetType = 'collection';//查询结果一定是数据集

3、数据库配置直接array该数据集  'resultset_type'  => 'collection',

数据集临时隐藏字段超级好用!!!

转换成数据集后 检查数据库查询数据是否为空则不能使用if(!result){} 而是

if($result->isEmpty()){}

修改器:当调用修改器作用的那个字段时触发:格式 在model 中定义get+首字母大写的字段+Attr($value[,$data]);

class Test extends Model{

        public function getStatusAttr($value,$data)
{
$status = [0=>'禁用',1=>'正常'];
return $status[$value];
}
} //控制器调用(任何地方调用都行)
$testData=\app\index\model\Test::get(1);
$status=$tstData->status;//输出正常
//or
$test=new app\index\model\Test;
$testData=$test->select();
$status=$testData[0]->status;//输出正常

修改器:和获取器一样 只是在修改作用的字段时触发

class Test extends Model{

        public function setNameAttr($value,$data)
{ return strtolower($value);
} public function setEmailAttr($value,$data)
{
return strtolower($value);
}
} $testmodel=new \app\index\model\Test;
$testmodel->save(['name'=>'LICHIHUA','email'=>'WOLICHIHUA2011@163.COM'],['id'=>2]);

自动添加和更新时间

model模型文件中添加:

protected $autoWriteTimestamp = true;// 开启自动写入时间戳字段(识别为int 对照自己的字段格式)    (支持int、datetime、timestamp、true、false)
// 定义时间戳字段名
protected $createTime = 'create_at';//默认create_time
protected $updateTime = 'update_at';//默认update_time false则是关闭自动写入update时间字段

全局设置:

数据库配置文件中添加:

// 开启、关闭自动写入时间戳字段(int、datetime、timestamp、true、false)
'auto_timestamp' => 'datetime',

其他属性:

class User extends Model
{
//只读字段,更新时排除列出的字段
protected $readonly = ['name','email']; //类型转换(将数据库查出的字段自动进行转换)
protected $type = [
'status' => 'integer',
'score' => 'float',
'birthday' => 'datetime',//timestamp
'info' => 'array',
//integer、float、boolean、array、object、serialize、json、timestamp、datetime
]; }

自动完成

class Test extends Model{
//写入(新增和修改)
protected $auto = [];
//新增
protected $insert = ['ip','status' => 1];
//修改
protected $update = ['login_ip']; protected function setIpAttr()
{
return request()->ip();
} protected function setLoginIpAttr()
{
return request()->ip();
}

查询范围 scop

model('user')->scop('thinkphp')->select();  会调用mode里自定义的scopeThinkphp($query)方法

class User extends Model{

    protected function scopeThinkphp($query)
{
$query->where('name','thinkphp')->field('id,name');
} protected function scopeAge($query)
{
$query->where('age','>',20)->limit(10);
}
} //调用
model('user')->scop('thinkphp')->select();
model('user')->scop('thinkphp,age')->select();
 

模型分层和控制器分层用法一样的

模型关联

ORM(对象关系映射)model就是对orm的实现  一般中小型项目用这个就好了 大型的估计就需要原生的sql好优化

模型之with()关联预载入

thinkphp5 with关联预载入

数据库:

\think\Db的__callStatic方法调用自身的connect方法获得config配置对应的驱动数据库实例如:\think\db\connector\Mysql

//\think\Db::table('think_user'); 则 下面调用的是
//self::connect()->table('think_user') 等价于
//new \think\db\builder\Mysql()->table(); 继承至Connection.php
//而table方法是Query.php里的
//这个Query类是什么时候怎么加载上的?
//Connection.php有个__construct 和 __call
//当调用Mysql(Connection)类里的不存在的方法时__call调动getQuery实例化获取新的查询对象 而实例化的类是__construct时获取的
//即Db::table实际调用的是Query类的table方法

原生查询:

//查询操作
Db::query('select * from think_user where id=?',[8]);
//or
Db::query('select * from think_user where id=:id',['id'=>8]);
//写入操作
Db::execute('insert into think_user (id, name) values (?, ?)',[8,'thinkphp']);
//or
Db::execute('insert into think_user (id, name) values (:id, :name)',['id'=>8,'name'=>'thinkphp']); 可以使用多个数据库连接,使用
Db::connect($config1)->query('select * from think_user where id=:id',['id'=>8]); //是在config.php配置的?额外数据库配置参数
/数据库配置1
'db_config1' => [
// 数据库类型
'type' => 'mysql',
// 服务器地址
'hostname' => '127.0.0.1',
// 数据库名
'database' => 'thinkphp',
// 数据库用户名
'username' => 'root',
// 数据库密码
'password' => '',
// 数据库编码默认采用utf8
'charset' => 'utf8',
// 数据库表前缀
'prefix' => 'think_',
],
//数据库配置2
'db_config2' => 'mysql://root:1234@localhost:3306/thinkphp#utf8';

实例化数据库:

//table方法必须指定完整的数据表名
$DB=Db::table('think_user')
//或者
$DB=db('user');助手函数

//数据库配置文件定义了后缀或者数据表无后缀则可用
$DB=Db::name('user')

闭包查询;

Db::select(function($query){
$query->table('think_user')->where('status',1);
});

查:

find  返回数据或者null

select 返回数据或空数组

增加;

insert($data);返回插入成功的条数

insertGetId($data);返回插入成功后的id

insertAll( $data)插入多条记录,返回插入成功的条数

删除:

delete()

修改:

update   update 方法返回影响数据的条数,没修改任何数据返回 0

更新某个字段的值

Db::table('think_user')->where('id',1)->setField('name', 'thinkphp');

自增或自减一个字段的值  setInc/setDec 如不加第二个参数,默认值为1   setInc/setDec 方法返回影响数据的条数

db('user')->where('id',1)->update(['name' => 'thinkphp']);
// 更新某个字段的值
db('user')->where('id',1)->setField('name','thinkphp');
// 自增 score 字段
db('user')->where('id', 1)->setInc('score');
// 自减 score 字段
db('user')->where('id', 1)->setDec('score');
// 获取`think_user`表所有信息
Db::getTableInfo('think_user');

链式操作

所有的连贯操作都返回当前的模型实例对象(this),其中带*标识的表示支持多次调用。

where*                           and查询(数组、字符串、对象)
whereOr* or查询(数组、字符串、对象)
table table('前缀_表名,[前缀_表名,...]') or table(array['think_user'=>'user','think_role'=>'role']); or table('__表名(大写)__')这种方式会自动获取表名的前缀
alias 设置别名 table('dl_user)->alias('u') 多个用数组方式alias(array('dl_user'=>'u','di_role'=>'r'));
field* 指定数据表操作字段 field('id,username as name,age') or field(array('id','username'=>'name',age))
order* order('id desc,age') or order(array('id'=>'desc','age'))
limit limit(10) limit(11,25)
page page(第几页,显示多少条)
group
having
join*
union* 用于对查询的union支持(字符串、数组、对象)
distinct 返回唯一不同的值 distinct(true)
lock 用于数据库的锁机制
cache 用于查询缓存
comment
fetchSql(true) 直接反返回sql 而不是结果
force*(索引名) 强制使用索引
bind*
partition 用于设置分表信息(数组or字符串)
strict 用于设置是否严格检测字段名是否存在(布尔)
failException 用于设置没有查询到数据是否抛出异常(布尔)
wheretime* 用于时间日期的快捷查询(字符串)
view* 视图查询
relation* 用于关联查询
with* 用于关联预载入
master 用于设置主服务器读取数据(布尔)
sequence 用于设置Pgsql的自增序列名(其他sql无用?)

查询表达式

where('字段名','表达式','查询条件');
whereOr('字段名','表达式','查询条件');

数操作函数:

外部可访问
Db:
static connect($config = [], $name = false) [Connection] 调用的是Connection下的connect方法
static clear() [void] 清除连接实例 connector/Mysql extends Connection:
getFields($tableName) [array] 取得数据表的字段信息
getTables($dbName = '')[array] 取得数据库的表信息 Connection:
getBuilder()[array] 获取当前连接器类对应的Builder类
fieldCase($info_arr)[array] 对返数据表字段信息进行大小写转换出来
getConfig($config = '')[mixed] 获取数据库的配置参数
setConfig($config, $value = '')[void] 设置数据库的配置参数
connect(array $config = [], $linkNum = 0, $autoConnection = false)[PDO] 连接数据库方法
free()[???] 释放查询结果
getPdo()[PDO|false] 获取PDO对象
query($sql, $bind = [], $master = false, $pdo = false)[mixed] 执行查询 返回数据集
execute($sql, $bind = [], Query $query = null)[int] 执行语句
getRealSql($sql, array $bind = [])[string] 根据参数绑定组装最终的SQL语句 便于调试 transaction($callback)[mixed] 执行数据库事务
startTrans()[bool|mixed] 启动事务
commit()[void] 用于非自动提交状态下面的查询提交
rollback()[void] 事务回滚 batchQuery($sqlArray = [], $bind = [], Query $query = null)[boolean] 批处理执行SQL语句 批处理的指令都认为是execute操作
getQueryTimes($execute = false)[integer] 获得查询次数
getExecuteTimes()[integer] 获得执行次数
close()[Connection自身] 关闭数据库(或者重新连接)
getLastSql()[string] 获取最近一次查询的sql语句
getLastInsID($sequence = null)[string] 获取最近插入的ID
getNumRows()[integer] 获取返回或者影响的记录数
getError()[string] 获取最近的错误信息
quote($str, $master = true)[string] SQL指令安全过滤
listen($callback)[void] 监听SQL执行 Query类
getConnection()[Connection类] 获取当前的数据库Connection对象
connect($config)[Query] 切换当前的数据库连接
getModel()[Model|null] 获取当前的模型对象实例
readMaster($allTable = false)[void] 设置后续从主库读取数据
getBuilder()[Builder类] 获取当前的builder实例对象 name($name)[Query] 指定默认的数据表名(不含前缀)
setTable($table)[Query] 指定默认数据表名(含前缀)
getTable($name = '')[string] 得到当前或者指定名称的数据表
parseSqlTable($sql)[string] 将SQL语句中的__TABLE_NAME__字符串替换成带前缀的表名(小写) query($sql, $bind = [], $master = false, $class = false)[mixed] 执行查询 返回数据集
xecute($sql, $bind = [])[int] 执行语句
getLastInsID($sequence = null)[string] 获取最近插入的ID
getLastSql()[string][string] 获取最近一次查询的sql语句
transaction($callback)[mixed] 执行数据库事务
startTrans()[void] 启动事务
commit()[void] 用于非自动提交状态下面的查询提交
rollback()[void] 事务回滚
batchQuery($sql = [], $bind = [])[boolean] 批处理执行SQL语句 批处理的指令都认为是execute操作
getConfig($name = '')[boolean] 获取数据库的配置参数 getPartitionTableName($data, $field, $rule = [])[string] 得到分表的的数据表名
value($field, $default = null, $force = false)[mixed] 得到某个字段的值
column($field, $key = '索引')[array] 得到某个列的数组
count($field = '*')[integer|string] COUNT查询
aggregate($aggregate, $field, $force = false)[mixed] 聚合查询
sum($field)[float|int] SUM查询
min($field, $force = true)[mixed] MIN查询
max($field, $force = true)[mixed] MAX查询
avg($field)[float|int] AVG查询
setField($field, $value = '')[integer] 设置记录的某个字段值 支持使用数据库字段和方法
setInc($field, $step = 1, $lazyTime = 0)[integer|true] 字段值(延迟)增长
setDec($field, $step = 1, $lazyTime = 0)[integer|true] 字段值(延迟)减少 join($join, $condition = null, $type = 'INNER')[Query] 查询SQL组装 join
union($union, $all = false)[Query] 查询SQL组装 union
field($field, $except = false, $tableName = '', $prefix = '', $alias = '')[Query] 指定查询字段 支持字段排除和指定数据表
fieldRaw($field, array $bind = [])[Query] 表达式方式指定查询字段
data($field, $value = null)[Query] 设置数据
inc($field, $step = 1)[Querey] 字段值增长
dec($field, $step = 1)[Querey] 字段值减少
exp($field, $value)[Query] 使用表达式设置数据
raw($value)[Expression] 使用表达式设置数据
view($join, $field = true, $on = null, $type = 'INNER')[Query] 指定JOIN查询字段
\think\Db::table('sky_user a')->view('sky_user b','username,password',"a.uid=b.uid",'INNER')->select();
等同于
\think\Db::table(['sky_user'=>"a"])->view(['sky_user'=>"b"],['username'=>"u","password"],"a.uid=b.uid",'INNER')->select();
partition($data, $field, $rule = [])[Query]    设置分表规则
where($field, $op = null, $condition = null)[Query] 指定AND查询条件
whereOr($field, $op = null, $condition = null)[Query] 指定OR查询条件
whereXor($field, $op = null, $condition = null)[Query] 指定XOR查询条件
whereRaw($where, $bind = [], $logic = 'AND')[Query] 指定表达式查询条件
whereOrRaw($where, $bind = [])[Query] 指定表达式查询条件 OR
whereNull($field, $logic = 'AND')[Query] 指定Null查询条件
whereNotNull($field, $logic = 'AND')[Query] 指定NotNull查询条件
whereIn($field, $condition, $logic = 'AND')[Query] 指定In查询条件
whereNotIn($field, $condition, $logic = 'AND')[Query] 指定NotIn查询条件
whereLike($field, $condition, $logic = 'AND')[Query] 指定Like查询条件
whereNotLike($field, $condition, $logic = 'AND')[Query] 指定NotLike查询条件
whereBetween($field, $condition, $logic = 'AND')[Query] 指定Between查询条件
whereNotBetween($field, $condition, $logic = 'AND')[Query] 指定NotBetween查询条件
whereExp($field, $condition, $logic = 'AND')[Query] 指定Exp查询条件
useSoftDelete($field, $condition = null)[Query] 设置软删除字段及条件
removeWhereField($field, $logic = 'AND')[Query] 去除某个查询条件
removeOption($option = true)[Query] 去除查询参数
limit($offset, $length = null)[Query] 指定查询数量
page($page, $listRows = null)[Query] 指定分页 $config =[
'page'=>1,//当前页
'path'=>1,//url路径
'query'=>1,//url额外参数
'fragment'=>1,//url锚点
'var_page'=>1,//分页变量
'list_rows'=>1,//每页数量
'type'=>1,//分页类名
];
paginate($listRows = null, $simple = false, $config = [])[\think\Paginator] 分页查询
table($table)[Query] 指定当前操作的数据表
using($using)[Query] SING支持 用于多表删除
order($field, $order = null)[Query] 指定排序 order('id','desc') 或者 order(['id'=>'desc','create_time'=>'desc'])
orderRaw($field, array $bind = [])[Query] 表达式方式指定Field排序
cache($key = true, $expire = null, $tag = null)[Query] 查询缓存
group($group)[Query] 指定group查询
having($having)[Query] 指定having查询
lock($lock = false)[Query] 指定查询lock(是否lock)
distinct($distinct)[Query] 指定distinct查询(是否唯一)
alias($alias)[Query] 指定数据表别名
orce($force)[Query] 指定强制索引
fetchSql($fetch = true)[Query] 获取执行的SQL语句
fetchPdo($pdo = true)[Query] 不主动获取数据集
master()[Query] 设置从主服务器读取数据
strict($strict = true)[Query] 设置是否严格检查字段名
failException($fail = true)[Query] 设置查询数据不存在是否抛出异常
sequence($sequence = null)[Query] 设置自增序列名
pk($pk)[Query] 指定数据表主键
whereTime($field, $op, $range = null)[Query] 查询日期或者时间 getTableInfo($tableName = '', $fetch = '')[mixed] 获取数据表信息
getPk($options = '')[string|array] 获取当前数据表的主键
getTableFields($table = '')[??] 获取当前数据表字段信息
getFieldsType($table = '')[??] 获取当前数据表字段类型
getFieldsBind($table = '')[??] 获取当前数据表绑定信息 bind($key, $value = false, $type = PDO::PARAM_STR)[Query] 参数绑定 isBind($key)[boolean] 检测参数是否已经绑定 options(array $options)[Query] 查询参数赋值 getOptions($name = '')[mixed] 获取当前的查询参数 with($with)[Query] 设置关联查询JOIN预查询
withCount($relation, $subQuery = true)[Query] 关联统计
withField($field)[Query] 关联预加载中 获取关联指定字段值
via($via = '')[Query] 设置当前字段添加的表别名
relation($relation)[Query] 设置关联查询
insert(array $data = [], $replace = false, $getLastInsID = false, $sequence = null)[integer|string] 插入记录
insertGetId(array $data, $replace = false, $sequence = null)[integer|string] 插入记录并获取自增ID
insertAll(array $dataSet, $replace = false, $limit = null)[integer|string] 批量插入记录
selectInsert($fields, $table)[integer|string] 通过Select方式插入记录
update(array $data = [])[integer|string] 更新记录
getPdo()[\PDOStatement|string] 执行查询但只返回PDOStatement对象
select($data = null)[Collection|false|\PDOStatement|string] 查找记录
find($data = null)[array|false|\PDOStatement|string|Model] 查找单条记录
selectOrFail($data = null)[array|\PDOStatement|string|Model] 查找多条记录 如果不存在则抛出异常
findOrFail($data = null)[array|\PDOStatement|string|Model] 查找单条记录 如果不存在则抛出异常
chunk($count, $callback, $column = null, $order = 'asc')[boolean] 分批数据返回处理
getBind()[array] 获取绑定的参数 并清空
buildSql($sub = true)[string] 创建子查询SQL
delete($data = null)[int] 删除记录
static event($event, $callback)[void] 注册回调方法

最新文章

  1. python(4) - 装饰器2
  2. SQL Server中时间段查询和数据类型转换
  3. cuda中时间用法
  4. hdu 4741 Save Labman No.004(2013杭州网络赛)
  5. RQNOJ PID4 / 数列(位运算)
  6. mysql之 mysql 5.6不停机主从搭建(一主一从)
  7. jsp网页连接mysql数据库
  8. SpringMVC集成rabbitmq:优化秒杀下单环节
  9. k8s重要概念及部署k8s集群(一)--技术流ken
  10. JQuery实现数组移除指定元素
  11. Angular4学习笔记(四)- 依赖注入
  12. webkit开源项目
  13. EGOCache缓存框架详细讲解
  14. openvpn-在Linux中安装和配置OpenVPN Server的最简便方法!(转)
  15. Good Bye 2017 部分题解
  16. 【转】TextView的详细属性
  17. Code Forces 20A BerOS file system
  18. Java伙伴系统(模拟)
  19. netcat、nc工具随记
  20. springboot的mvn与gradle启动方式

热门文章

  1. android高级页面效果集锦
  2. easyui生成合并行,合计计算价格
  3. Ionic 2: ReferenceError: webpackJsonp is not defined
  4. day 28 面向对象 三种特性之一 多态 鸭子类型 反射(反省)
  5. 使用Spring配置数据源JdbcTemplate
  6. LeetCode(67):二进制求和
  7. MySQL5.7.20报错Access denied for user &#39;root&#39;@&#39;localhost&#39; (using password: NO)
  8. JMeter 中对于Json数据的处理方法
  9. linux基础练习题(1)
  10. mysql集群7.4.1