模型:Model 用于实现数据表的所有操作
前面讲过的Db类,同样能完成数据表的数据处理,写起来也更加的灵活,但因为没有考虑使用面向对象中的“封装”,会出现代码的冗余,可能对日后的维护带来麻烦
废话少说,如何定义模型呢,要注意哪些问题呢
1、模型也是一个类文件,必须放在模块目录的model目录下
2、模型的代码结构:自定义的模型必须继承think\Model类
<?php
namespace app\index\model;
use think\Model;
class Student extends Model
{
}
3、模型的类名也有讲究
模型会自动对应数据表,模型类的命名规则是除去表前缀的数据表名称,采用驼峰法命名,并且首字母大
写,例如:
模型名 | 约定对应数据表(假设数据库的前缀定义是 think_) |
User | think_user |
UserType | think_user_type |
所以,Student模型对应的数据表是 前缀_student 表
如果你的规则和上面的系统约定不符合,那么需要设置Model类的数据表名称属性,以确保能够找到对应的数
据表。
<?php
namespace app\index\model;
use think\Model;
class Student extends Model
{
// 设置当前模型对应的完整数据表名称, 必须是 $table ,不能是其它名字
protected $table = 'student';
}
4、模型的使用
<?php
namespace app\index\controller;
use app\index\model\Student;
use think\Exception;
class Index
{
public function index()
{
//将要添加的数据
$data = [
'no' => '1835050001',
'name' => '张三',
'sex' => '男',
'age' => 20
];
//实例化模型对象
$stu = new Student();
try {
$count = $stu->save($data); //返回影响的行数
return $count;
} catch (Exception $ex) {
return '添加错误,' . $ex->getMessage();
}
}
}