【PHP】ThinkPhp6期末速通

目录

    • 一、安装Composer
    • 二、设置Composer下载源
    • 三、Composer下载,安装TinkPHP6
    • 四、安装成功后 目录结构
    • 五、运行
  • ThinkPHP6 起步
    • 一、MVC
    • 二、单应用模式访问
      • 调试
    • 三、安装视图
    • 四、模板渲染
      • 默认访问
      • 指定访问
    • 五、模板变量
      • 默认赋值
      • 助手函数(若不使用默认赋值的话)
  • ThinkPHP6模板引擎
    • 一、运算符
    • 二、模板函数
      • 原样输出
        • html内编译php
    • 三、循环标签
      • foreach 循环
      • volist 循环
      • for循环
    • 四 判断标签
      • if判断
      • switch判断
      • 条件标签
      • 比较标签
  • ThinkPHP6数据库
    • 数据库管理软件
    • 链接数据库
    • 原生SQL语句
      • 原生查询
      • 原生插入和更新
    • 框架操作
      • 查询操作
        • 单条记录查询find
        • 多条数据查询 select
        • 查询某个字段的值value
        • 查询某一列的值column
      • 添加
        • 添加一条数据insert
          • insertGetId方法添加数据成功返回添加数据的自增主键
        • 添加多条数据insertAll
          • insertAll方法添加数据成功返回添加成功的条数
      • 修改
        • 修改数据update
        • 自增inc
        • 自减dec
      • 删除
        • 删除数据delete
        • 软删除useSoftDelete
      • 其他操作
  • ThinkPHP6模型
    • 一、创建模型
    • 二、模型操作
      • 1、find查询数据
      • 2、controller怎么调用model
      • 3、select查询数据
      • 4、数据转换toArray()
      • 5、新增数据
      • 6、修改数据
      • 7、删除数据
    • 三、模型设置
      • 1、name和table
      • 2、pk改变主键名称
      • 3、schema设置模型对应数据表字段及类型
      • 4、disuse数据表废弃字段(数组)
    • 四、模型的主要功能
      • 1、获取器
      • 2、修改器
      • 3、搜索器
      • 4、检查数据

一、安装Composer

第一步:双击下载好的composeri运行程序
第二步:选择要安装的盘符
第三步:选择php版本。如果你是集成包环境,就到集成包里找php
第四步:全部下一步

二、设置Composer下载源

先设置composer的下载源,也是镜像地址
在命令行窗口或控制台输入aliyun的镜像

composer config -g repo.packagist composer https://mirrors.aliyun.com/composer

三、Composer下载,安装TinkPHP6

先切换到php环镜根目录

cd D:/phpEnv/www

执行下载Thinkphpe6命令。最后的tp,是新建个p目录,可更改

composer create-project topthink/think tp

如果要更新的话执行下面命令即可,不能在www里运行,在tp6文件夹里运行更新命令

composer update topthink/framework

四、安装成功后 目录结构

6.0版本目录结构的主要变化是核心框架纳入vendor目录,然后原来的application目录变成app目录。
安装后的目录结构就是一个单应用模式
在mac或者1inux环境下面,注意需要设置runtime目录权限为777

【PHP】ThinkPhp6期末速通_第1张图片

五、运行

·注:咱们只讲windows系统里的php环境集成包,如何访问
第一步:打开phpstudy集成软件-》站点域名管理
第二步:网站域名:www.xxx.com
第三步:网站目录:tp/public
第四步:在C:\Windows\System32 drivers\etc目录下,打开hosts文件
第五步:最后一行输入127.0.0.1www.Xx.com
第六步:直接在览器上输入域名(wwx.com)

ThinkPHP6 起步

ThinkPHP支持传统的MVC(Model-.VMew-Controller)模式以及流行的MVWM(Model–VMew-ViewModel)模式的应用
开发教程里面我们以mvc为例子讲解

一、MVC

mvc软件系统分为三个基本部分:模型(Model)、视图(Vew)和控制器(Controller)
ThinkPHP6是一个典型的MvC架构

控制器-控制器,用于将用户请求转发给相应的Model进行处理,并根据Modd的计算结果向用户提供相应响应
视图·为用户提供使用界面,与用户直接进行交互。
模型,承载数据,并对用户提交请求进行计算的模块。

MVC架构程序的工作流程:
(1)用户通过View页面向服务端提出请求,可以是表单请求、超链接请求、AJAX请求等
(2)服务端Controller控制器接收到请求后对请求进行解析,找到相应的Model对用户请求进行处理
(3)Model处理后,将处理结果再交给Controller
(4)Controller在接到处理结果后,根据处理结果找到要作为向客户端发回的响应VMew页面。页面经這染(数据填
充)后,再发送给客户端。

模型:数据库增删改查、算法等

控制器:view和model的桥梁

【PHP】ThinkPhp6期末速通_第2张图片

二、单应用模式访问

【PHP】ThinkPhp6期末速通_第3张图片

入口文件是:

【PHP】ThinkPhp6期末速通_第4张图片

【PHP】ThinkPhp6期末速通_第5张图片

  1. controller下的php文件只能有一个class类,class类名必须和文件名保持一致

调试

显示错误信息,改成true即可

【PHP】ThinkPhp6期末速通_第6张图片

三、安装视图

【PHP】ThinkPhp6期末速通_第7张图片

composer require topthink/think-view

需要在cmd中进入tp文件夹里面执行命令

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-oWC49lhV-1685785920771)(C:\Users\Administrator\Desktop\ThinkPHP6\image-20230530183749427.png)]

默认view(需手动创建)和control目录同级,若要修改config/view.php

【PHP】ThinkPhp6期末速通_第8张图片

【PHP】ThinkPhp6期末速通_第9张图片

四、模板渲染

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-3ccGYlrY-1685785920772)(C:\Users\Administrator\Desktop\ThinkPHP6\image-20230530184340830.png)]


namespace app\controller;

use app\BaseController;

use think\facade\view;//需引入

class Index extends BaseController
{
    public function index()
    {
        return view::fetch();//默认访问controller的目录view/index(控制器or类)/index(方法).html
    }

    public function hello($name = 'ThinkPHP6')
    {
        return 'hello,' . $name;
    }
    public function login(){
        return 'login';
    }
}

【PHP】ThinkPhp6期末速通_第10张图片

默认访问

view::fetch() 默认访问view/当前控制器名的小写(即index)/index.html(方法名.html)

【PHP】ThinkPhp6期末速通_第11张图片

指定访问

将view::fetch()指定参数index/index,访问view/index/index.html

【PHP】ThinkPhp6期末速通_第12张图片

【PHP】ThinkPhp6期末速通_第13张图片

五、模板变量

默认赋值

【PHP】ThinkPhp6期末速通_第14张图片

View::assign(a,b) 表示键值对,a变量即传入前端view中的变量,b是a的取值

app/view/index/index.html

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
name:{$name}
<br/>
qq:{$qq}
body>
html>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-KMGbFyMM-1685785920773)(C:\Users\Administrator\Desktop\ThinkPHP6\image-20230530190837992.png)]


namespace app\controller;

use app\BaseController;

use think\facade\view;

class Index extends BaseController
{
    public function index()
    {
        return view::fetch('index/index',[
            'name'=>'1',
            'qq'=>'2'
        ]);
    }
}

View::fetch()中,index/index表示需要渲染的页面,第二个即数组变量

助手函数(若不使用默认赋值的话)

不建议使用助手函数,效率比上述方法低

app/controller/Index.php


namespace app\controller;

use app\BaseController;

use think\facade\view;//需引入

class Index extends BaseController
{
    public function index()
    {
        return view('index/index',[
            'name'=>'1',
            'qq'=>'2'
        ]);// 其中index/index可以指定
    }

}

app/view/index/index.html

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
name:{$name}
<br/>
qq:{$qq}
body>
html>

【PHP】ThinkPhp6期末速通_第15张图片

ThinkPHP6模板引擎

【PHP】ThinkPhp6期末速通_第16张图片

一、运算符

【PHP】ThinkPhp6期末速通_第17张图片

app/controller/Index.php


namespace app\controller;

use app\BaseController;

use think\facade\view;//需引入

class Index extends BaseController
{
    public function index()
    {
        return view('index/index',[
            'a'=>2,
            'b'=>3
        ]);// 其中index/index可以指定
    }

}

app/view/index/index.html

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
a+b={$a+$b}

    
    
body>
html>

【PHP】ThinkPhp6期末速通_第18张图片

二、模板函数

【PHP】ThinkPhp6期末速通_第19张图片

【PHP】ThinkPhp6期末速通_第20张图片

【PHP】ThinkPhp6期末速通_第21张图片
【PHP】ThinkPhp6期末速通_第22张图片

  1. default函数,若$default 变量存在则显示default变量,若不存在则显示default="小鱼"这个默认值
  2. substr=0,3 表示截取前3个字符

【PHP】ThinkPhp6期末速通_第23张图片

模板注释阻止编译,html注释无法阻止编译,即前端注释可以在前端通过查看源码看到,而模板注释看不到

【PHP】ThinkPhp6期末速通_第24张图片

原样输出

app/controller/Index.php


namespace app\controller;

use app\BaseController;

use think\facade\view;//需引入

class Index extends BaseController
{
    public function index()
    {
        return view('index/index',[
            'a'=>2,
            'b'=>3
        ]);// 其中index/index可以指定
    }

}

app/view/index/index.html

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
a+b={$a+$b}
<br/>
{literal} 
a+b={$a+$b}
{/literal}
body>
html>

literal内不进行编译

【PHP】ThinkPhp6期末速通_第25张图片

html内编译php

app/view/index/index.html




    
    Title


{php}
echo "小鱼";
{/php}


【PHP】ThinkPhp6期末速通_第26张图片

三、循环标签

foreach 循环

app/controller/Index.php


namespace app\controller;

use app\BaseController;

use think\facade\view;//需引入

class Index extends BaseController
{
    public function index()
    {
        $arr=[
            [
                'id'=>1,
                'name'=>'小鱼'
            ],
            [
                'id'=>2,
                'name'=>'小夏'
            ]
        ];
        View::assign('arr',$arr);
        return View::fetch();
    }

}

app/view/index/index.html

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>

{foreach $arr as $item}
<div>
    <span>id:{$item['id']}span>
    <span>name:{$item['name']}span>
div>
{/foreach}


{foreach $arr as $index=>$item}
<div>
    <span>{$index} id:{$item['id']}span>
    <span>{$index} name:{$item['name']}span>
div>
{/foreach}

body>
html>

【PHP】ThinkPhp6期末速通_第27张图片

volist 循环

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-8153jrzE-1685785920776)(C:\Users\Administrator\Desktop\ThinkPHP6\image-20230530193731483.png)]

app/controller/Index.php


namespace app\controller;

use app\BaseController;

use think\facade\view;//需引入

class Index extends BaseController
{
    public function index()
    {
        $arr=[
            [
                'id'=>1,
                'name'=>'小鱼'
            ],
            [
                'id'=>2,
                'name'=>'小夏'
            ]
        ];
        View::assign('arr',$arr);
        return View::fetch();
    }

}

app/view/index/index.html

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>

{volist name="arr" id="item" key="k" offset="1" length="1"}
<div>
    <span>{$K} id:{$item['id']}span>
    <span>{$K} name:{$item['name']}span>
div>
{/volist}
body>
html>

for循环

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-TIZmKp2S-1685785920776)(C:\Users\Administrator\Desktop\ThinkPHP6\image-20230530194408943.png)\

app/view/index/index.html

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>

{for start="1" end="10" }
{$i}
<br/>
{/for}
body>
html>

【PHP】ThinkPhp6期末速通_第28张图片

四 判断标签

if判断

app/controller/Index.php


namespace app\controller;

use app\BaseController;

use think\facade\view;//需引入

class Index extends BaseController
{
    public function index()
    {
       View::assign('status',1);
       View::assign('week',3);
       return View::fetch();
    }

}

app/view/index/index.html

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>

{if $status == 1}
/if标签表示结束<br/>
{/if}

{if $week==1}

{elseif $week==3/}
elseif和else结合的判断方法
{else /}

{/if}
body>
html>

【PHP】ThinkPhp6期末速通_第29张图片

switch判断

app/view/index/index.html

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>

{switch  $week}
{case 0}<div>星期日div>{/case}
{case 3}<div>星期三div>{/case}
{/switch}
body>
html>

【PHP】ThinkPhp6期末速通_第30张图片

条件标签

【PHP】ThinkPhp6期末速通_第31张图片

比较标签

【PHP】ThinkPhp6期末速通_第32张图片

ThinkPHP6数据库

【PHP】ThinkPhp6期末速通_第33张图片

数据库管理软件

  1. phpMyAdmin(网页数据库管理)
  2. Navicat for MySql(windows软件数据库管理)

此处使用phpEnv软件中的phpMyAdmin,登录账号是root,密码是mysql的密码

【PHP】ThinkPhp6期末速通_第34张图片

链接数据库

config/database.php



return [
    // 默认使用的数据库连接配置
    'default'         => env('database.driver', 'mysql'),

    // 自定义时间查询规则
    'time_query_rule' => [],

    // 自动写入时间戳字段
    // true为自动识别类型 false关闭
    // 字符串则明确指定时间字段类型 支持 int timestamp datetime date
    'auto_timestamp'  => true,

    // 时间字段取出后的默认时间格式
    'datetime_format' => 'Y-m-d H:i:s',

    // 时间字段配置 配置格式:create_time,update_time
    'datetime_field'  => '',

    // 数据库连接配置信息
    'connections'     => [
        'mysql' => [
            // 数据库类型
            'type'            => env('database.type', 'mysql'),
            // 服务器地址
            'hostname'        => env('database.hostname', '127.0.0.1'),
            // 数据库名
            'database'        => env('database.database', 'mall'),
            // 用户名
            'username'        => env('database.username', 'root'),
            // 密码
            'password'        => env('database.password', '12345678'),
            // 端口
            'hostport'        => env('database.hostport', '3306'),
            // 数据库连接参数
            'params'          => [],
            // 数据库编码默认采用utf8
            'charset'         => env('database.charset', 'utf8'),
            // 数据库表前缀
            'prefix'          => env('database.prefix', ''),

            // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器)
            'deploy'          => 0,
            // 数据库读写是否分离 主从式有效
            'rw_separate'     => false,
            // 读写分离后 主服务器数量
            'master_num'      => 1,
            // 指定从服务器序号
            'slave_no'        => '',
            // 是否严格检查字段是否存在
            'fields_strict'   => true,
            // 是否需要断线重连
            'break_reconnect' => false,
            // 监听SQL
            'trigger_sql'     => env('app_debug', true),
            // 开启字段缓存
            'fields_cache'    => false,
        ],

        // 更多的数据库配置信息
    ],
];

原生SQL语句

原生查询

app/controller/Index.php


namespace app\controller;

use app\BaseController;

use think\facade\view;//需引入

use think\facade\db;//引入 执行数据库原生查询

class Index extends BaseController
{
    public function index()
    {
//       原生查询,query只能进行查询,不能进行别的操作如插入(可以插入,但是看不到结果)
        $query=Db::query("SELECT * from receiver");
        dump($query);//显示结果
    }

}

此时的receiver表,如下:

【PHP】ThinkPhp6期末速通_第35张图片

输出结果如下:

【PHP】ThinkPhp6期末速通_第36张图片

原生插入和更新

app/controller/Index.php


namespace app\controller;

use app\BaseController;

use think\facade\view;//需引入

use think\facade\db;//引入 执行数据库原生查询

class Index extends BaseController
{
    public function index()
    {
//       原生执行,可以使用execute进行插入和更新
        $execute=Db::execute("INSERT INTO `receiver` (`id`, `user_id`, `name`, `phone`, `address`, `is_default`) VALUES ('2', '2', '李四', '119119', '医院门诊', '1')");
        dump($execute);//显示插入受影响的记录
        $update=Db::execute("UPDATE `receiver` set `is_default`='0' where `id`='2' ");
        dump($update);//显示更新受影响的记录

        $query=Db::query("SELECT * from receiver");
        dump($query);
    }

}

【PHP】ThinkPhp6期末速通_第37张图片

框架操作

查询操作

单条记录查询find

若查询结果不存在返回null,否则返回结果数组(原生查询会返回对象,需要通过转换才能转为数组)

app/controller/Index.php


namespace app\controller;

use app\BaseController;

use think\facade\view;//需引入

use think\facade\db;//引入 执行数据库原生查询

class Index extends BaseController
{
    public function index()
    {
        $find = Db::table('receiver')->find(1);//table(表名字),find(主键)
        dump($find);
    }

}

结果:【PHP】ThinkPhp6期末速通_第38张图片

多条数据查询 select

select方法查询结果是一个二维数组,如果结果不存在,返回空数组

app/controller/Index.php


namespace app\controller;

use app\BaseController;

use think\facade\view;//需引入

use think\facade\db;//引入 执行数据库原生查询

class Index extends BaseController
{
    public function index()
    {
        $select=Db::table('receiver')->select();//查询所有数据
        dump($select);
    }

}

结果【PHP】ThinkPhp6期末速通_第39张图片

查询某个字段的值value

value方法查询结果不存在,返回null

app/controller/Index.php


namespace app\controller;

use app\BaseController;

use think\facade\view;//需引入

use think\facade\db;//引入 执行数据库原生查询

class Index extends BaseController
{
    public function index()
    {
        $value=Db::table('receiver')->value('name');//查询字段为name的记录,默认是查询第一条记录
        print_r($value);
    }

}

【PHP】ThinkPhp6期末速通_第40张图片

查询某一列的值column

column方法查询结果不存在,返回空数组

app/controller/Index.php


namespace app\controller;

use app\BaseController;

use think\facade\view;//需引入

use think\facade\db;//引入 执行数据库原生查询

class Index extends BaseController
{
    public function index()
    {
        $column=Db::table('receiver')->column('name');//查询字段为name的所有记录
        print_r($column);
        $column2=Db::table('receiver')->column('name','id');//查询字段为name和id的所有记录,id与name一一对应
        print_r($column2);
    }

}

【PHP】ThinkPhp6期末速通_第41张图片

添加

添加一条数据insert

insert方法添加数据成功返回添加成功的条数,通常情况返回1

app/controller/Index.php


namespace app\controller;

use app\BaseController;

use think\facade\view;//需引入

use think\facade\db;//引入 执行数据库原生查询

class Index extends BaseController
{
    public function index()
    {
        $data=['user_id'=>'1','name'=>'洛丽塔','phone'=>'13420020232','address'=>'广东省华南师范大学','is_default'=>'1'];
        $insert=Db::table('receiver')->insert($data);
        print_r($insert);
    }

}

【PHP】ThinkPhp6期末速通_第42张图片

此时的数据库为

【PHP】ThinkPhp6期末速通_第43张图片

若需要知道添加完后的id,可以使用下面的insertGetId方法(即先插入后查询)

insertGetId方法添加数据成功返回添加数据的自增主键

app/controller/Index.php


namespace app\controller;

use app\BaseController;

use think\facade\view;//需引入

use think\facade\db;//引入 执行数据库原生查询

class Index extends BaseController
{
    public function index()
    {
        $data=['user_id'=>'2','name'=>'lenck','phone'=>'13267629111','address'=>'广东省华南师范大学','is_default'=>'1'];
        $insert=Db::table('receiver')->insertGetId($data);
        print_r($insert);
    }

}

![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-gtVAUwus-1685785920780)(C:\Users\Administrator\Desktop\ThinkPHP6\image-20230601184915728.png)](https://img-blog.csdnimg.cn/4e4c9bed9be74af2a50842350bd2ed9d.png)

添加多条数据insertAll
insertAll方法添加数据成功返回添加成功的条数

app/controller/Index.php


namespace app\controller;

use app\BaseController;

use think\facade\view;//需引入

use think\facade\db;//引入 执行数据库原生查询

class Index extends BaseController
{
    public function index()
    {
        $data=[
            ['user_id'=>'2','name'=>'lenck','phone'=>'13267629111','address'=>'广东省东软学院','is_default'=>'0'],
            ['user_id'=>'4','name'=>'黄宇辰','phone'=>'13267629112','address'=>'广东省华南师范大学','is_default'=>'1'],
            ['user_id'=>'6','name'=>'徐炯','phone'=>'13267629151','address'=>'广东省华南理工','is_default'=>'1']
        ];//键名需要与数据表的字段名一致,顺序可以不一致,可以为空的字段可以不填,不能为空的一定要填
        $insert=Db::table('receiver')->insertAll($data);
        print_r($insert);
    }

}

插入了3条记录

【PHP】ThinkPhp6期末速通_第44张图片

修改

修改数据update

update方法返回影响数据的条数,没修改任何数据返回0

app/controller/Index.php


namespace app\controller;

use app\BaseController;

use think\facade\view;//需引入

use think\facade\db;//引入 执行数据库原生查询

class Index extends BaseController
{
    public function index()
    {
        $data=['address'=>'广西庄'];
        $insert=Db::table('receiver')->where('id',1)->update($data);//此处需要用where指定,不然会把所有记录都修改
        print_r($insert);
    }

}

修改了1条记录

【PHP】ThinkPhp6期末速通_第45张图片

自增inc

inc方法自增一个字段的值

app/controller/Index.php


namespace app\controller;

use app\BaseController;

use think\facade\view;//需引入

use think\facade\db;//引入 执行数据库原生查询

class Index extends BaseController
{
    public function index()
    {
        $inc=Db::table('receiver')->where('id',2)->inc('phone')->update();
        print_r($inc);//phone字段值自增1
        $inc=Db::table('receiver')->where('id',2)->inc('phone',5)->update();
        print_r($inc);//phone字段值自增5
    }

}

自减dec

dec方法自减一个字段的值

app/controller/Index.php


namespace app\controller;

use app\BaseController;

use think\facade\view;//需引入

use think\facade\db;//引入 执行数据库原生查询

class Index extends BaseController
{
    public function index()
    {
        $dec=Db::table('receiver')->where('id',2)->dec('phone')->update();
        print_r($dec);//phone字段值自增1
        $dec=Db::table('receiver')->where('id',2)->dec('phone',5)->update();
        print_r($dec);//phone字段值自增5
    }

}

删除

删除数据delete

delete方法返回影响数据的条数,没有删除返回0

app/controller/Index.php


namespace app\controller;

use app\BaseController;

use think\facade\view;//需引入

use think\facade\db;//引入 执行数据库原生查询

class Index extends BaseController
{
    public function index()
    {
        $delete=Db::table('receiver')->where('name','张三')->delete();//删除name字段为张三的记录
        print_r($delete);
        $delete=Db::table('receiver')->delete(2);//删除主键为2的记录
        print_r($delete);
        $delete=Db::table('receiver')->delete(true);//删除表receriver中的所有数据
        print_r($delete);
    }

}

软删除useSoftDelete

并未真正删除,只是改状态

业务数据不建议真实删除数据,TP系统提供了软删除机制

$delete = Db::table('receiver')->useSoftDelete('id',3)->delete();
print_r($delete);

其他操作

save方法统一写入数据,自动判断是新增还是更新数据(以写入数据中是否存在主键数据为依据)

// 添加数据
$data=['user_id'=>'1','name'=>'洛丽塔','phone'=>'13420020232','address'=>'广东省华南师范大学','is_default'=>'1'];
$save=Db::table('receiver')->save($data);
print_r($save);

// 修改数据
$data=['id'=>3,'phone'=>'123123123'];
$save=Db::table('receiver')->save($data);
print_r($save);

ThinkPHP6模型

  • 请确保你已经在数据库配置文件中配置了数据库连接信息
  • 模型会自动对应数据表,模型类的命名规则是除去表前缀的数据表名称,采用驼峰法命名,并且首字母大写
  • 模型自动对应的数据表名称都是遵循小写+下划线规范,如果你的表名有大写的情况,必须通过设置模型的table属性。

一、创建模型

【PHP】ThinkPhp6期末速通_第46张图片

​ 此处应该是模型名字对应数据表名字,而不是数据库

我使用的数据表是receiver,所以我创建一个Receiver的模型

二、模型操作

在模型中可以进行数据库操作(上述讲的数据库操作都可以)

【PHP】ThinkPhp6期末速通_第47张图片

1、find查询数据

find获取单条数据,返回的是当前模型的对象实例

app/model/Receiver.php



namespace app\model;

use think\Model;

class Receiver extends Model
{
    public function find(){
        $find=Receiver::where('id',2)->find();
        return $find;
    }
}

2、controller怎么调用model

find(主键id)查询,只使用数据表主键为id的使用主键,非id会查询失败

app/controller/Test.php



namespace app\controller;
use app\model\Receiver;//引用模型类
class Test{
    public function index(){
        $db=new Receiver();
        $index=$db->find();
        print_r($index);
    }
}

在url中输入:tp.tp/index.php/test/index

【PHP】ThinkPhp6期末速通_第48张图片

3、select查询数据

select获取多条数据,返回的是当前模型的对象实例

app/model/Receiver.php



namespace app\model;

use think\Model;

class Receiver extends Model
{
    public function find(){
        $find=Receiver::where('id','>',2)->select();
        $find=$find->toArray();//转数组返回
        return $find;
    }
}

【PHP】ThinkPhp6期末速通_第49张图片

4、数据转换toArray()

5、新增数据

create静态方法添加数据,返回的是当前模型的对象实例

app/model/Receiver.php



namespace app\model;

use think\Model;

class Receiver extends Model
{
    public function create(){
        $create=Receiver::create([
            'user_id'=>8,
            'name'=>'李白',
            'phone'=>'12313123123',
            'address'=>'广东省囧雪',
            'is_default'=>'1'
         
        ]);
        //echo $create->id;//直接获取自增id
        return $create;
        
    }
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-74WvbC4s-1685785920782)(C:\Users\Administrator\Desktop\ThinkPHP6\image-20230601194247942.png)]

6、修改数据

update静态方法修改数据,返回的是当前模型的对象实例

save在取出数据后,更改字段更新数据。这种方式是最佳的更新方式

【PHP】ThinkPhp6期末速通_第50张图片

【PHP】ThinkPhp6期末速通_第51张图片

id是需要修改的记录,改成第一个数组那样

7、删除数据

【PHP】ThinkPhp6期末速通_第52张图片

三、模型设置

【PHP】ThinkPhp6期末速通_第53张图片

【PHP】ThinkPhp6期末速通_第54张图片

1、name和table

当你的数据表没有前缀的时候,name和table属性的定义是没有区别的,定义任何一个即可

app/model/Receiver.php



namespace app\model;

use think\Model;

class Receiver extends Model
{
    protected $name='Receiver';
    //name和table属性任选其一即可,都是选择表的意思,name属性值需要首字母大写,因为它实际上是指代模型名称
//    protected $table='receiver';
    public function test(){
        $select=Receiver::where('id',1)->select();
        return $select -> toArray();
    }
}

name和table结果都是一样的

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-waVnwS23-1685785920783)(C:\Users\Administrator\Desktop\ThinkPHP6\image-20230601195623208.png)]

2、pk改变主键名称

model默认的主键是id,若主键不是id,则需要pk进行改变主键名称


<?php

namespace app\model;

use think\Model;

class Receiver extends Model
{
    protected $name='Receiver';
    //name和table属性任选其一即可,都是选择表的意思,name属性值需要首字母大写,因为它实际上是指代模型名称
//    protected $table='receiver';
    protected $pk='uid';
    public function test(){
        $select=Receiver::where('id',1)->select();
        return $select -> toArray();
    }
}

3、schema设置模型对应数据表字段及类型

  • 默认会自动获取(包括字段类型),但自动获取会导致增加一次查询
  • schema属性一旦定义,就必须定义完整的数据表字段类型
  • 类型根据php数据类型定义,如果是json类型直接定义为json即可

【PHP】ThinkPhp6期末速通_第55张图片

4、disuse数据表废弃字段(数组)

若有某字段不想要,则可以使用disuse废弃

【PHP】ThinkPhp6期末速通_第56张图片

四、模型的主要功能

1、获取器

  • 获取器的作用是对模型实例的(原始)数据做出自动处理
  • 命名规则:get+字段名+Attr
  • 字段名是数据表字段的驼峰转换

比如字段性别中,1表示男性,0表示女性,则可以通过模型进行转换

【PHP】ThinkPhp6期末速通_第57张图片

此处数据表的字段是status,所以获取器的名字是getStatusAttr,若数据表的字段有下划线如user_id,则获取器的名字是getUserIdAttr

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-WgX6RAUz-1685785920784)

例如将时间戳改成日期

【PHP】ThinkPhp6期末速通_第58张图片

2、修改器

  • 修改器的主要作用是对模型设置的数据对象值进行处理
  • 命名规则:set+字段名+Attr

【PHP】ThinkPhp6期末速通_第59张图片

3、搜索器

  • 搜索器的作用是用于封装字段(或者搜索标识)的查询条件表达式
  • 命名规则:search+字段名+Attr

【PHP】ThinkPhp6期末速通_第60张图片

搜索器只能在withSearch才能实现

4、检查数据

  • 如果要判断数据集是否为空,不能直接使用判断
  • 必须使用数据集对象的isEmpty方法判断

【PHP】ThinkPhp6期末速通_第61张图片

你可能感兴趣的:(PHP,php,开发语言,后端)