Thinkphp 使用Model来增删改查

这里写目录标题

一、Model部分

php 复制代码
<?php
namespace app\common\model;

use think\Model;
use think\Request;
use think\Db;
use traits\model\SoftDelete;

class Visit Extends Model
{
    // use SoftDelete;
    // 开启自动写入时间戳字段
    protected $name = 'visit_log';
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';
    protected $append = [

    ];

    protected $alias = 'u';

    public function user(){
        return $this->belongsTo('User', 'uid', 'id', [], 'LEFT')->bind(['username'=>'username']);
    }
}

二、增加

php 复制代码
public function add(){
   $log = new ModelVisit;

   $log->uid = $this->auth->id;
   $log->gid = $this->auth->group_id;
   $log->visit_time = input('visit_time');
   $log->status = input('status');
   $log->status = 1;

   if($log->save()){
       $this->success("ok");
   }else{
       $this->error("添加失败,请稍后再试");
   }
}

三、查询

php 复制代码
public function list(){
     $row = ModelVisit::with('user')->where('gid',$this->auth->group_id)->order("id","desc")->select();
     foreach ($row as $k => $v) {
         $v->visit_time = datetime($v->visit_time, 'Y/m/d');
     }
     if($row){
         $this->success('ok',$row);
     }else{
         $this->error("查询失败,请稍后再试");
     }
 }

四、删除

php 复制代码
public function del(){
    $id = input('id');
    $ret = ModelVisit::get($id);
    if (!$ret) {
        $this->error('记录不存在');
    }
    ModelVisit::destroy($id);
    $this->success('删除成功');
}

五、修改

php 复制代码
public function edit(){
        $id = input('id');
        $row = ModelVisit::get($id);
        if (!$row) {
            $this->error('记录不存在');
        }
        $log = [];

        $log['visit_time'] = input('visit_time');
        $log['visit_type'] = input('visit_type');

        if($row->allowField(true)->save($log) === false){
            $this->error('修改失败');
        }
        $this->success('修改成功');
    }
相关推荐
mobai76 分钟前
使用pyang将yang模型转换为xml
xml·运维·服务器
捞的不谈~9 分钟前
解决在Ubuntu系统下使用Lucid 相机(HTR003S-001)-Ubuntu 20.04系统遇到GLIBC和GLIBCXX版本不兼容的问题
linux·运维·ubuntu
TG_yunshuguoji20 分钟前
腾讯云代理商:腾讯云部署OpenClaw 如何接入自定义大模型?
服务器·云计算·腾讯云·openclaw
洛菡夕23 分钟前
LVS+Keepalived高可用群集
运维·服务器·lvs
智能运维指南26 分钟前
2026 运维监控选型指南:全栈智能可观测平台如何选?
运维
卢傢蕊27 分钟前
LVS+Keepalived 高可用群集
linux·运维·lvs·keepalived
Heart_to_Yang28 分钟前
TPLink路由器虚拟专用网端口映射故障问题,端口转发无效
运维·服务器·网络
艾莉丝努力练剑29 分钟前
【Linux线程】Linux系统多线程(六):<线程同步与互斥>线程同步(上)
java·linux·运维·服务器·c++·学习·线程
姚不倒30 分钟前
构建高可用可观测性平台:VictoriaMetrics 集群 + VictoriaLogs 统一接入实践
运维·docker·微服务·云原生·架构
Gofarlic_OMS36 分钟前
中小企业控制方法:中小型制造企业Creo许可证成本控制
java·大数据·运维·算法·matlab·制造