1、模型的常用属性
<?php
namespace app\model;
use think\Model;
class Test extends Model
{
//绑定表
protected $name='test';//name不加前缀
// protected $table='bloggo_test';//table要加表名
//绑定主键
protected $pk='test_id';//不加默认为id
// //也可指定数据库连接
// //connection属性使用用配置参数名(需要在数据库配置文件中的connections参数中添加对应标识)。
// protected $connection='bloggo';
// 设置字段自动转换类型,比较适用
protected $type=[
'test_title'=>'string'
];
//也可设置《所有》字段名信息,以避免多次开销
protected $schema=[
'test_id'=>'int',
'test_text'=>'json',
'test_title'=>'string'
];
}
2、模型的增删改查
<?php
namespace app\controller;
use app\BaseController;
use app\model\Test as TestModel;
class Test extends BaseController
{
//查找
private function find1(){
//获取第三条数据
return TestModel::find(7);//7为id对应的条目
}
//插入操作
private function action1(){
$test=new TestModel();
$test->test_title='123@qq.com';//严格区分大小写
// //也支持以下写法
// $test['test_title']='123@qq.com';
$test->allowField(['test_title'])->save();//只允许某些字段插入
}
//新增多条
private function action2(){
$list=[
['name'=>'Jack','test_title'=>'html'],
['name'=>'Jack','test_title'=>'hello world']
];
$test=new TestModel();
$test->allowField(['test_title'])->saveAll($list);
}
//save方法在查询之后操作就是更新,没有查询进行就是插入
//通过数据直接更新
private function action3(){
$data=[
'name'=>'Jack',
'test_title'=>'23333'
];
$test=TestModel::find(7);//修改第7条数据
$test->allowField(['test_title'])->save($data);
}
//通过update实现更新
private function action4(){
//这里记得传入id
TestModel::update(['test_title'=>'123','test_id'=>7]);
}
//先查找,后删除
private function action5(){
TestModel::find(8)->delete();
}
//更据主键删除
private function action6(){
TestModel::destroy(10);
// //支持批量多个数据
// TestModel::destroy([1,2,3]);
}
//游标查询,对于大量数据时使用,开销较小
private function action7(){
$cursor=TestModel::where('test_id',">",0)
->cursor();
foreach ($cursor as $item){
echo $item['test_title'];
}
}
//查询方法类似于Db的查找详情见Db博客
//查询结果转数组
private function array0(){
$test=TestModel::find(11)
->toArray();
var_dump($test);
}
}