一、一般情况下,模型是和一张数据表绑定的,数据表中的所有字段就变成了该模型类的属性;
二、模型文件名称一定要和绑定的数据表名称相同(不含表前缀),模型文件名称首字母大写;
三、用户自定义模型一定需要继承于公共模型,所以TP5.1需要导入公共的模型类 use think\Model,并继承该类;
四,绑定模型以后,在进行数据库操作时就不需要去选择数据表,并且返回的始终是个对象;
控制器单条查询写法示例
<?php
namespace app\index\controller;
use app\index\model\Student;
use think\Db;
class Index{
public function get(){
//dump(Student::get(4));
$res = Student::field('id,name,email')->where('id',3)->find();
// 不使用模型的查询语句
//$res = Db::table('student')->field('id,name,email')->find();
dump($res);
}
}说明:
控制器首页需要引入Student类:use app\index\model\Student;
通过 Student::的方式构造查询语句,如上例指定输出查询字段;
b::table('student')与Student::效果相同;
控制器多条查询写法示例
public function all(){
$res = Student::field('id,name')->where('id','in','1,2,3')->select();
dump($res);
}
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号