摘要:如何定义一个模型<?php namespace app\index\model; use think\Model; class Staff extends Model { }2.模型的实例化<?php namespace app\index\controller; use think\Controller;
如何定义一个模型
<?php
namespace app\index\model;
use think\Model;
class Staff extends Model
{
}2.模型的实例化
<?php
namespace app\index\controller;
use think\Controller;
use app\index\model\Staff;
class Demo1 extends Controller
{
public function instance()
{
//模型实例化
$staff = new Staff();
}
}还可以通过依赖注入的方式实例化模型
<?php
namespace app\index\controller;
use think\Controller;
use app\index\model\Staff;
class Demo1 extends Controller
{
public function instance(Staff $staff)
{
}
}3.模型的查询操作
get():查询单条记录
all():查询多条记录
$staff = Staff::get(1);//查询主键为1的记录
$staff = Staff::all([1,2,3]);查询主键为1,2,3的记录
支持闭包查询
$satff = Staff::get(function($query){
$query->where('age','>',30)->where('salary','>',5000);
});$satff = Staff::all(function($query){
$query->where('age','>',30)->where('salary','>',5000);
});4.模型的更新操作
save()方法更新
$staff = Staff::get(1); $staff->name = '神雕大侠'; $staff->save();
update()静态方法更新
Staff::update(['name'=>'杨过'],['staff_id'=>1]);
5.模型的新增操作
$data = [ 'name'=> '金轮法王', 'sex' => '0', 'age' => 50, 'salary'=> 5000 ]; $field = ['name','sex','age','salary']; Staff::create($data,$field);
6.模型的删除操作
delete方法删除
$staff = Staff::get(1); $staff->delete();
destroy静态方法删除
Staff::destroy(1);
7.软删除
软删除步骤:
1.在表中添加一个字段:删除时间:delete_time
2.在模型类添加一个属性:$deleteTime = 'delete_time'
3.在模型中导入软删除的trait类库:SoftDelete
4.最新版支持设置软删除的默认字段值:$defaultSoftDelete = 0
<?php
namespace app\index\model;
use think\Model;
use think\model\concern\SoftDelete;
class Staff extends Model
{
use SoftDelete;
//设置数据表的名称
protected $table = 'staff';
//设置主键:默认为id
protected $pk = 'staff_id';
//设置删除时间的字段名
protected $deleteTime = 'delete_time';
//设置软删除字段的默认值
protected $defaultSoftDelete = 0;
}软删除数据
Staff::destroy(4);
批改老师:天蓬老师批改时间:2018-11-21 09:08:49
老师总结:模型的基本操作,都在这里呢, 很不错,多多动手写写