thinkphp6 模型

这篇博客详细介绍了 ThinkPHP6 框架中模型的使用,包括模型类的命名规范,如何去除表前缀并启用驼峰式命名,以及如何在配置文件 `config/database.php` 中开启字段缓存和全局模型自动时间戳功能。
摘要由CSDN通过智能技术生成

模型类需要去除表前缀(tp_),采用驼峰式命名,并且首字母大写;

tp_user(表名) => User
tp_user_type(表名) => UserType

为了减少内存,需要在 config/database.php 开启字段缓存;

// 开启字段缓存
'fields_cache' => true,

如果想全局开启’模型自动时间戳’,在 database.php 中,设置为 true;

// 自动写入时间戳字段
'auto_timestamp' => true,
'auto_timestamp' => 'datetime',//设置自动时间戳为datetime类型
	<?php //模型php文件 User.php
		namespace app\index\model;

		use think\Model;

		class User extends Model
		{
   

			use SoftDelete;//开启软删除
			protected $deleteTime = 'delete_time';//设置软删除字段
			protected $defaultSoftDelete = 0;//delete_time 默认为 null,如不是,可自定义
			
			protected $pk = 'user_id';//默认主键为 id,设置其他为user_id

			protected $table = 'tp_one';//默认数据表为tp_user,设置其他为tp_one

			protected $autoWriteTimestamp = true;//开启自动时间戳
			protected $autoWriteTimestamp = 'datetime';//设置自动时间戳为datetime类型
			protected $createTime = 'create_at';//修改自动时间戳——创建字段
			protected $createTime = false;//不需要 自动时间戳——创建字段 的时候
			protected $updateTime = 'update_at';//修改自动时间戳——修改字段
			protected $updateTime = false;//不需要 自动时间戳——修改字段 的时候

			protected $readonly = ['username', 'email'];//只读字段,不允许被修改
			protected $disuse = ['status', 'uid'];//废弃字段,读取会忽略,写入忽略(存疑,未验证);

			protected $json = ['list'];//设置 json 字段的字符字段;

			// *************************************//
			protected static function init(){
   //模型初始化,第一次实例化的时候执行 init
				
				echo '初始化 User 模型';
			}
			// *************************************//
			public function getStatusAttr($value){
   //模型获取器。get“Status”Attr。(在获取数据时,把Status值转换为别的数据)
				$status = [-1=>'删除', 0=>'禁用', 1=>'正常', 2=>'待审核'];
				return $status[$value];
			}
			
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值