模型

模型类通常完成实际的业务逻辑和数据封装,并返回和格式无关的数据

定义模型

定义一个User模型

<?php
namespace app\model;

// 引用底层模型
use think\Model;

class User extends Model
{
    // 设置当前模型对应的完整数据表名称
    protected $table = 'think_user';
}

模型的数据操作

新增

// 添加一条数据
$user           = new User;
$user->name     = 'thinkphp';
$user->email    = 'thinkphp@qq.com';
$user->save();

// 直接传入数据到save方法批量赋值
$user = new User;
$user->save([
    'name'  =>  'thinkphp',
    'email' =>  'thinkphp@qq.com'
]);

// 获取自增ID
$user           = new User;
$user->name     = 'thinkphp';
$user->email    = 'thinkphp@qq.com';
$user->save();
// 获取自增ID
echo $user->id;

// 如果你的主键不是id,而是user_id的话
$user           = new User;
$user->name     = 'thinkphp';
$user->email    = 'thinkphp@qq.com';
$user->save();
// 获取自增ID
echo $user->user_id;

// 批量添加
$user = new User;
$list = [
    ['name'=>'thinkphp','email'=>'thinkphp@qq.com'],
    ['name'=>'onethink','email'=>'onethink@qq.com']
];
$user->saveAll($list);

更新

// 查询出数据后,更改字段内容后使用save方法更新数据
$user = User::find(1);
$user->name     = 'thinkphp';
$user->email    = 'thinkphp@qq.com';
$user->save();

// 使用update方法
$user = new User;
$data = ['name' => 'thinkphp', 'email'=>'thinkphp@qq.com'];
// update('更新的数据','更新条件','允许字段','数据表后缀'),如果第一个参数里面有主键的话,那么第二个参数(更新条件)无需再传入
$user->update($data,['id' => 1]);

// 批量更新数据
$user = new User;
$list = [
    ['id'=>1, 'name'=>'thinkphp', 'email'=>'thinkphp@qq.com'],
    ['id'=>2, 'name'=>'onethink', 'email'=>'onethink@qq.com']
];
$user->saveAll($list);

删除

// 查询后调用delete方法
$user = User::find(1);
$user->delete();

// 直接调用静态方法(根据主键删除)
User::destroy(1);
// 支持批量删除多个数据
User::destroy([1,2,3]);

查询

// 取出主键为1的数据
$user = User::find(1);
// 输出name值
echo $user->name;

// 使用查询构造器查询满足条件的数据
$user = User::where('name', 'thinkphp')->find();
// 输出name值
echo $user->name;

// 根据主键获取多个数据
$list = User::select([1,2,3]);
// 对数据集进行遍历操作
foreach($list as $key=>$user){
    echo $user->name;
}

// 使用查询构造器查询
$list = User::where('status', 1)->limit(3)->order('id', 'asc')->select();
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::count();
User::where('status','>',0)->count();
User::where('status',1)->avg('score');
User::max('score');

// 如果你的字段不是数字类型,是使用max/min的时候,需要加上第二个参数
User::max('name', false);

获取器

获取器的作用是对模型实例的(原始)数据做出自动处理的特殊方法,方法命名规范为getFieldNameAttr(该方法必须为public类型)

用法示例

<?php
namespace app\model;

use think\Model;

class User extends Model 
{
    public function getStatusAttr($value)
    {
        $status = [-1=>'删除',0=>'禁用',1=>'正常',2=>'待审核'];
        return $status[$value];
    }
}

数据表的字段会自动转换为驼峰法,一般status字段的值采用数值类型,我们可以通过获取器定义,自动转换为字符串描述。

$user = User::find(1);
echo $user->status; // 例如输出“正常”

获取器还可以定义数据表中不存在的字段,例如

<?php
namespace app\model;

use think\Model;

class User extends Model 
{
    // 获取器方法的第二个参数传入的是当前的所有数据数组
    public function getStatusTextAttr($value,$data)
    {
        $status = [-1=>'删除',0=>'禁用',1=>'正常',2=>'待审核'];
        return $status[$data['status']];
    }
}

我们就可以直接使用status_text字段的值了

$user = User::find(1);
echo $user->status_text; // 例如输出“正常”

修改器

和获取器相反,修改器的主要作用是对模型设置的数据对象值进行处理,修改器方法的命名规范为setFieldNameAttr,例如

<?php
namespace app\model;

use think\Model;

class User extends Model 
{
    public function setNameAttr($value)
    {
        return strtolower($value);
    }
}

如下代码实际保存到数据库中的时候会转为小写

$user = new User();
$user->name = 'THINKPHP';
$user->save();
echo $user->name; // thinkphp

批量修改

除了赋值的方式可以触发修改器外,还可以用下面的方法批量触发修改器

$user = new User();
$data['name'] = 'THINKPHP';
$data['email'] = 'thinkphp@qq.com';
$user->data($data, true);
$user->save();
echo $user->name; // thinkphp

或者直接使用save方法触发,例如

$user = new User();
$data['name'] = 'THINKPHP';
$data['email'] = 'thinkphp@qq.com';
$user->save($data);
echo $user->name; // thinkphp

自动时间戳

系统支持自动写入创建和更新的时间戳字段(默认关闭),有两种方式配置支持

第一种方式是全局开启,在数据库配置文件中进行设置

config\database.php

// 开启自动写入时间戳字段
'auto_timestamp' => true,

第二种是在需要的模型类里面单独开启

<?php
namespace app\model;

use think\Model;

class User extends Model
{
    protected $autoWriteTimestamp = true;
}

又或者首先在数据库配置文件中全局开启,然后在个别不需要使用自动时间戳写入的模型类中单独关闭

<?php
namespace app\model;

use think\Model;

class User extends Model
{
    protected $autoWriteTimestamp = false;
}

定义时间字段

<?php
namespace app\model;

use think\Model;

class User extends Model 
{
    // 数据表字段不是默认值,那么可以这样定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    // 只需要使用createtime字段而不需要自动写入updatetime,则可以单独关闭某个字段
    protected $updateTime = false;

}

或者在数据库配置文件中统一定义时间字段

'datetime_field' => 'createtime,updatetime',

支持动态关闭时间戳写入功能,例如你希望更新阅读数的时候不修改更新时间,可以使用isAutoWriteTimestamp方法

$user = User::find(1);
$user->read +=1;
$user->isAutoWriteTimestamp(false)->save();

软删除

要使用软删除功能,需要引入SoftDelete trait,例如User模型按照下面的定义就可以使用软删除功能

<?php
namespace app\model;

use think\Model;
// 引用软删除模型
use think\model\concern\SoftDelete;

class User extends Model
{
    use SoftDelete;
    // 软删除字段
    protected $deleteTime = 'deletetime';
}

定义好模型后,我们就可以使用

// 软删除
User::destroy(1);
// 真实删除
User::destroy(1,true);

$user = User::find(1);
// 软删除
$user->delete();
// 真实删除
$user->force()->delete();

默认情况下查询的数据不包含软删除数据,如果需要包含软删除的数据,可以使用下面的方式查询

User::withTrashed()->find();
User::withTrashed()->select();

如果仅仅需要查询软删除的数据,可以使用

User::onlyTrashed()->find();
User::onlyTrashed()->select();

恢复被软删除的数据

$user = User::onlyTrashed()->find(1);
$user->restore();
powered by GitbookEdit Time: 2023-04-08 10:28:32