首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

ThinkPHP 批次刪除資料完整實作:陣列主鍵與單一主鍵雙支援

     編輯:PHP 相關知識

前端表單設計

關鍵點:checkbox name="id[] 陣列格式,value 為主鍵值。


        
ID 標題 操作
{$vo.id} {$vo.title} 編輯

控制器刪除方法

public function delete()
{
    $ids = $this->request->param('id/a');  // 獲取陣列參數
    $model = $this->model;  // BaseController 注入的模型實例
    
    if (empty($ids)) {
        $this->error('請選擇要刪除的資料');
    }
    
    // 構建 WHERE 條件
    if (is_array($ids)) {
        $where = ['id' => ['in', $ids]];
    } else {
        $where = ['id' => $ids];
    }
    
    // 執行刪除
    $result = $model->where($where)->delete();
    
    if ($result !== false) {
        $this->success("成功刪除 {$result} 筆資料");
    } else {
        $this->error('刪除失敗:' . $model->getError());
    }
}

進階:軟刪除支援

// Model 開啟軟刪除
protected $deleteTime = 'delete_time';

// 控制器邏輯不變,$result 為影響行數
// 實際執行 UPDATE 設定 delete_time 而非 DELETE

進階:關聯資料級聯刪除

public function delete()
{
    $ids = $this->request->param('id/a');
    
    Db::startTrans();
    try {
        // 1. 刪除主表
        $mainModel = model('Article');
        $mainModel->where('id', 'in', $ids)->delete();
        
        // 2. 刪除關聯表(評論、標籤、附件等)
        model('Comment')->where('article_id', 'in', $ids)->delete();
        model('ArticleTag')->where('article_id', 'in', $ids)->delete();
        model('Attachment')->where('article_id', 'in', $ids)->delete();
        
        Db::commit();
        $this->success('批次刪除成功');
    } catch (\Exception $e) {
        Db::rollback();
        $this->error('刪除失敗:' . $e->getMessage());
    }
}

安全性加強

  1. 權限驗證:刪除前檢查用戶是否擁有資料擁有權或管理員權限
  2. CSRF 保護:表單包含 {:token()},控制器驗證 $this->request->token()
  3. 記錄操作日誌:記錄刪除者、時間、資料 ID、IP
  4. 限制批次數量:if (count($ids) > 100) $this->error('單次最多刪除 100 筆');

RESTful API 風格

// 路由:DELETE /articles/batch
public function batchDelete()
{
    $ids = $this->request->post('ids/a');  // JSON: {"ids": [1,2,3]}
    
    $result = model('Article')->destroy($ids);  // TP5+ destroy 支援陣列
    
    return json([
        'code' => $result ? 0 : 1,
        'msg'  => $result ? "刪除 {$result} 筆" : '刪除失敗',
        'data' => ['deleted_ids' => $ids]
    ]);
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved