目录
0x00插入操作
在模块下创建一个model文件夹和controller文件夹同级.
在model下创建文件,文件名和后台数据库的表名对应,例如你有一个user表(如果config中定义了表的前缀的话,文件名应该是去掉前缀后的名字),就创建一个User.php文件
然后在controller文件夹下创建一个UserController.php文件。
那么当涉及到关于用户的操作时,首先会进UserController.php,然后UserController.php调用User.php。
$this->save(关联数组);
$this->allowField(数组 或 逗号分隔的字符串 或者 true) 设置允许插入的字段
如果传true 那么 会自动过滤掉表中没有的字段,将表中有的字段插入。
$this->allowField(true)->save(关联数组)
$this->id 返回数据库中最后一条数据的id
演示:
UserController.php
<?php
namespace app\admin\controller;
use think\Controller;
use app\admin\model\User;
class UserController extends Controller{
public function index(){
$data = ['username'=>'zhouxingchi','pwd'=>'213435','reg_time'=>'2131245','user_email'=>'123@qq.com'];
$user = new User;
$user->getUserInfo($data);
}
}
User.php
<?php
namespace app\admin\model;
use think\Model;
class User extends Model{
public function getUserInfo($data){
echo "this is Model";
dump($data);
$this->data($data);
$ret = $this->save();
dump($ret);
}
}
不需要选择表名,因为文件名已经表明了表名。 如果文件名和要操作的表名不对应的话,可以在类中重载 protected $table=表名 来指定表名,不推荐这样使用。
方法二:将要插入的值设置成User方法的属性,通过这种方式实现数据的传递;
<?php
namespace app\admin\controller;
use think\Controller;
use app\admin\model\User;
class UserController extends Controller{
public function index(){
$data = ['username'=>'zhouxingchi','pwd'=>'213435','reg_time'=>'2131245','user_email'=>'123@qq.com'];
$user = new User;
$user->username=$data['username'];
$user->pwd=$data['pwd'];
$user->reg_time=$data['reg_time'];
$user->user_email=$data['user_email'];
$user->getUserInfo();
}
}
User.php
<?php
namespace app\admin\model;
use think\Model;
class User extends Model{
public function getUserInfo(){
$ret = $this->save();
dump($ret);
}
}
如果想插入多条的话,$data改成二维数组,然后使用saveAll($data)即可,不用data()函数
User.php
<?php
namespace app\admin\model;
use think\Model;
class User extends Model{
public function getUserInfo($data){
$ret = $this->saveAll($data);
dump($ret);
}
}
UserController.php
<?php
namespace app\admin\controller;
use think\Controller;
use app\admin\model\User;
class UserController extends Controller{
public function index(){
$data =[
['username'=>'zhouxingchi','pwd'=>'213435','reg_time'=>"123432",'user_email'=>'2314@qq.com'],
['username'=>'zhoulibo','pwd'=>'213435','reg_time'=>"123432",'user_email'=>'2314@qq.com']
];
$user = new User;
$user->getUserInfo($data);
}
}
0x01 查询操作
获取一条数据:
class User extends Model{
public function getUserInfo($data){
$res = self::get(4);
dump($res->toArray());
}
}
如果想查询特定数据,将条件封装成数组,例如['username'=>'zhang']传给get()即可。或者用
$this->where('id','1')->find()来查,返回值是一个collocation对象。
获取多条数据:
class User extends Model{
public function getUserInfo($data){
$res = self::all([1,3,4,5,6,7,8]);
dump($res->toArray());
}
}
get和all都是Model中的静态方法,在类中调用自己的静态方法,建议使用self::
返回的$res是一个对象,在database.php中可以将其修改为Collection对象
database.php中数据集返回类型一共有两种:array 和 collection,使用collection类型更有利于我们处理查询到的数据。
这样就可以调用collection对象的一些方法先预处理$res,然后再toArray()将其转成数组。
collection类包含以下方法:
查询某列的值:
获取一条
$res = User::where('username','JackChen')->value('pwd');
dump($res);
获取多条数据:
$res = User::where('username','JackChen')->column('pwd');
dump($res);
方法二:
public function getUserInfo($data){
$res = $this->field(['username','pwd'])->find();
dump($res->toArray());
}
动态查询:
getBy字段名:
字段名首字母大写,如果字段名是用下划线分割开的话,那么两头都大写,如user_name=>User_Name
$res = User::getByUsername('zhouxingchi');
dump($res->toArray());
排序:
->order('update_time DESC')
如果有多个排序规则,例如先安装权重排序,权重相同的按照更新时间排序
->order('weight DESC','update_time DESC')
0x02 更新数据
更新一条数据:
如果在save(,加上条件)的话就是更新操作,不加条件就是插入操作;
$data = ['username'=>'liyuan','pwd'=>'falllove'];
$this->save($data,['id'=>4]);
方法二:
$data = ['username'=>'liyuan','pwd'=>'falllove'];
$this->where('id',11)->update($data);
更新多条数据:
$data = [
['username'=>'liyuan1','pwd'=>'falllove','id'=>6],
['username'=>'liyuan2','pwd'=>'falllove','id'=>7],
['username'=>'liyuan3','pwd'=>'falllove','id'=>8]];
$this->saveAll($data);
saveAll可以自动识别是多行插入操作还是多行更新操作,识别依据:$data中是否包含主键,如果包含主键,则是根据主键进行的多行更新操作;
0x03删除操作
删除一条数据:先获取再删除
方法一:
$res = self::get(11)->delete();
dump($res);
方法二:
public function getUserInfo($data){
$res = $this->where('id',13)->delete();
dump($res);
}
删除多条数据:
方法一:
实例一:默认根据主键删除
$res = self::destroy([11,12,15]);
dump($res);
实例二:
$res = self::destroy(['username'=>'liyuan']);
dump($res);
方法二:
$res = self::where('id','>','12')->delete();
dump($res);
0x04 聚合函数
$sum = $this->count();
$max = $this->max('reg_time');
$min = $this->min('reg_time');
$avg = $this->avg('reg_time');
dump([$sum,$max,$min,$avg]);
0x05时间戳
第一种方式在database.php中auto_timestamp改为true,自动写入时间戳字段,不建议开启,如果开启,数据库中所有表中都需要有时间戳的字段。
第二种方式:直接在单独的模型类中设置
重载protected $autoWriteTimestamp=true;(作用范围仅限于对应表)则在插入数据时,会向表中create_time字段(插入时间)和update_time字段(最后一次更新时间)中自动插入时间戳。
当然前提是表结构中要加入这两个字段
alter table user add column update_time int not null;
alter table user add column create_time int not null;
<?php
namespace app\admin\model;
use think\Model;
class User extends Model{
protected $autoWriteTimestamp=true;
//如果想修改字段名也可以
//protected $createTime='create_at';
//protected $updateTime='update_at';
public function getUserInfo($data){
$res = $this->save(['username'=>'wuhan','pwd'=>'jiayou','reg_time'=>'123']);
dump($res);
}
}
如果想关闭updatetime,设置protected $updateTime = false;
需要修改什么配置,就在子类中重载什么配置,例如:
protected $dateFormat="Y-m-d H:i:s";
父类Model中相关配置如下:
// 数据库查询对象池
protected static $links = [];
// 数据库配置
protected $connection = [];
// 父关联模型对象
protected $parent;
// 数据库查询对象
protected $query;
// 当前模型名称
protected $name;
// 数据表名称
protected $table;
// 当前类名称
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;
0x06关联模型
一对一关联:
现在我们有要个有User.php模型,我们要给这个模型关联一个UserInfo.php模型,
在model下创建UserInfo.php文件:
<?php
namespace app\admin\model;
use think\Model;
class UserInfo extends Model{
}
创建对应的数据表
User.php
<?php
namespace app\admin\model;
use think\Model;
class User extends Model{
public function getUserInfo($data){
//2.查询UserInfo表的内容
dump(self::get(8)->userInfo->toArray());
}
public function userInfo(){
//1.将UserInfo表和User表关联起来,user_id对应id
return $this->hasOne('UserInfo','user_id','id');
}
}
注:
hasOne('关联模型名','外键名','主键名',[模型别名定义],'join类型')
关联新增:即如何向关联的表中插入数据
class User extends Model{
public function getUserInfo($data){
//2.首先从User表中查id=8的数据,然后调用userInfo将User表与UserInfo关联起来,然后用save向UserInfo表中插入数据
self::get(10)->userInfo()->save(['email'=>'Zhang@qq.com','mobile'=>'123456789']);
}
public function userInfo(){
//1.将UserInfo表和User表关联起来,user_id对应id
return $this->hasOne('UserInfo','user_id','id');
}
}
注意:关联新增userInfo需要加括号,关联更新userInfo不需要加括号。
关联更新:如何更新关联表中的数据
<?php
namespace app\admin\model;
use think\Model;
class User extends Model{
public function getUserInfo($data){
//2.首先从User表中查id=8的数据,然后调用userInfo将User表与UserInfo关联起来,然后用save更新UserInfo表中的数据
self::get(10)->userInfo->save(['email'=>'Zhang@qq.com','mobile'=>'123321']);
}
public function userInfo(){
//1.将UserInfo表和User表关联起来,user_id对应id
return $this->hasOne('UserInfo','user_id','id');
}
}
一对多关联:
即主表的一个id可以对应副表的几条数据;
插入方法和查询方法同一对一一样;唯一的区别在于关联表的时候,hasOne要变成hasMany
<?php
namespace app\admin\model;
use think\Model;
class User extends Model{
public function getUserInfo($data){
self::get(8)->userInfo()->save(['email'=>'Liu@qq.com','mobile'=>'123321']);
$res = self::get(8)->userInfo->toArray();
dump($res);
}
public function userInfo(){
//1.将UserInfo表和User表关联起来,user_id对应id
return $this->hasMany('UserInfo','user_id','id');
}
}
如果只想在查询时返回特定字段,可以在hasMany后面加个->field('字段名')