關鍵點: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());
}
}
{:token()},控制器驗證 $this->request->token()if (count($ids) > 100) $this->error('單次最多刪除 100 筆');// 路由: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]
]);
}