萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

ThinkPHP CURD 操作實戰要點總結

ThinkPHP 的 CURD (Create/Update/Read/Delete) 方法鏈極其強大,但新手常踩坑。本文結合用戶管理實例,總結 CURD 核心用法、常見錯誤與最佳實踐,助你寫出優雅、高效的模型操作代碼。

基礎模型定義

<?php
namespace app\admin\model;
use think\Model;

class User extends Model {
    protected $table = 'users';      // 可省略(按規約 user -> users)
    protected $pk = 'id';            // 主鍵
    protected $autoWriteTimestamp = true; // 自動維護 create_time/update_time
    protected $createTime = 'created_at';
    protected $updateTime = 'updated_at';
    protected $dateFormat = 'Y-m-d H:i:s'; // 讀取時格式化
}

控制器實戰

<?php
namespace app\admin\controller;
use app\admin\model\User;
use think\facade\View;
use think\facade\Request;

class UserController extends BaseController {
    // 列表 (Read)
    public function index() {
        $users = User::order('id', 'desc')->paginate(15);
        View::assign('users', $users);
        return View::fetch();
    }

    // 新增頁面
    public function create() {
        return View::fetch();
    }

    // 執行新增
    public function store() {
        $data = Request::post(['username','email','password','status']);
        // 驗證器建議單獨類,此處簡寫
        if (empty($data['username']) || empty($data['password'])) {
            return json(['code'=>0, 'msg'=>'用戶名/密碼必填']);
        }
        $data['password'] = password_hash($data['password'], PASSWORD_ARGON2ID);
        $user = User::create($data);
        return json(['code'=>1, 'msg'=>'創建成功', 'id'=>$user->id]);
    }

    // 編輯頁面
    public function edit($id) {
        $user = User::find($id);
        if (!$user) return $this->error('用戶不存在');
        View::assign('user', $user);
        return View::fetch();
    }

    // 執行更新
    public function update($id) {
        $user = User::find($id);
        if (!$user) return json(['code'=>0, 'msg'=>'用戶不存在']);
        $data = Request::post(['email','status','password']);
        if (!empty($data['password'])) {
            $data['password'] = password_hash($data['password'], PASSWORD_ARGON2ID);
        } else {
            unset($data['password']); // 不修改密碼
        }
        $user->save($data);
        return json(['code'=>1, 'msg'=>'更新成功']);
    }

    // 刪除
    public function delete($id) {
        $user = User::find($id);
        if (!$user) return json(['code'=>0, 'msg'=>'用戶不存在']);
        $user->delete();
        return json(['code'=>1, 'msg'=>'刪除成功']);
    }

    // 批量操作示例
    public function batch() {
        $ids = Request::post('ids/a'); // 強制數組
        $action = Request::post('action'); // delete/enable/disable
        if (empty($ids)) return json(['code'=>0, 'msg'=>'未選擇項目']);

        switch ($action) {
            case 'delete':
                User::destroy($ids);
                break;
            case 'enable':
                User::whereIn('id', $ids)->update(['status'=>1]);
                break;
            case 'disable':
                User::whereIn('id', $ids)->update(['status'=>0]);
                break;
            default:
                return json(['code'=>0, 'msg'=>'未知操作']);
        }
        return json(['code'=>1, 'msg'=>'批量操作完成']);
    }
}

模板片段 (index.html)

<table class="table">
    <thead><tr><th>ID</th><th>用戶名</th><th>郵箱</th><th>狀態</th><th>註冊時間</th><th>操作</th></tr></thead>
    <tbody>
    {volist name="users" id="vo"}
    <tr>
        <td>{$vo.id}</td>
        <td>{$vo.username}</td>
        <td>{$vo.email}</td>
        <td>
            <span class="badge {eq name="vo.status" value="1"}bg-success{else}bg-danger{/eq}">
                {eq name="vo.status" value="1"}正常{else}禁用{/eq}
            </span>
        </td>
        <td>{$vo.created_at}</td>
        <td>
            <a href="{:url('edit', ['id'=>$vo.id])}" class="btn btn-sm btn-primary">編輯</a>
            <button class="btn btn-sm btn-danger btn-delete" data-id="{$vo.id}">刪除</button>
        </td>
    </tr>
    {/volist}
    </tbody>
</table>
{: $users->render() } <!-- 分頁 -->

核心要點速查

操作方法關鍵點
單條查詢find($id) / where(...)->find()返回模型對象/ null
多條查詢select() / where(...)->select()返回模型集合
分頁paginate($size)自動處理 page 參數,模板 {: $list->render()}
新增create($data) / save($data)返回模型實例,自動回填自增 ID
更新$model->save($data) / where(...)->update($data)前者觸發模型事件/修改器,後者直接 SQL
刪除$model->delete() / destroy($ids) / where(...)->delete()destroy 支援數組批量刪除
字段自增/減setInc('field', $step) / setDec()原子操作,適合點讚、閱讀數
JSON 字段->json(['field'=>['key']]) 查詢 / json_set() 更新MySQL 5.7+ / PostgreSQL 支援

常見坑點與避雷

  1. 未開啟字段嚴格模式:protected $strict = true; 防止多餘字段寫入數據庫報錯或被忽略。
  2. 修改器/獲取器命名:setXxxAttr / getXxxAttr (TP6) 或 setXxxAttribute (TP5),注意駝峰轉下劃線。
  3. 軟刪除:use SoftDelete; protected $deleteTime = 'deleted_at';,查詢自動加 WHERE deleted_at IS NULL。
  4. 事務包裹:多表關聯操作必須用 Db::transaction(function(){ ... });。
  5. 模型事件:beforeInsert/afterInsert/beforeUpdate/afterUpdate/beforeDelete/afterDelete 集中處理關聯邏輯(如刪除用戶同步刪除訂單)。
  6. 字段類型轉換:$type = ['status'=>'boolean', 'tags'=>'array', 'config'=>'json']; 自動雙向轉換。

進階:查詢構建器鏈式調用

User::where('status', 1)
    ->where('created_at', '>', '2024-01-01')
    ->whereLike('username', '%keyword%')
    ->whereIn('id', [1,2,3])
    ->order(['id'=>'desc', 'login_count'=>'asc'])
    ->field('id,username,email,status')
    ->limit(10)
    ->select();

掌握 ThinkPHP CURD 的核心方法、模型事件、查詢構建器,能讓數據層代碼既簡潔又強大,是 TP 開發者必修的內功。

copyright © 萬盛學電腦網 all rights reserved