CodeIgniter 4 删除 Post 方法

CodeIgniter 4 delete Post Method

大家好

在这个 get 删除之前我必须注意我已经尝试搜索这个但我仍然不明白为什么它不起作用

请有人帮我解决这个问题我试了几个星期了,我不知道为什么我的删除按钮不起作用我在代码 igniter3 上做了它,它起作用了,但我似乎无法理解为了工作,因为我还在学习并且是新手,我想做的就是用我创建的按钮删除 post!请解释一下我做错了什么,这样我就可以了解这只是一个自学 code igniter 4 的测试项目,非常感谢 抱歉我的英语不好

这是我的代码

型号(Newsmodel.php)

<?php

namespace App\Models;

use CodeIgniter\Model;

class NewsModel extends Model
{
 protected $table = 'news';

 protected $allowedFields = ['title', 'slug', 'body'];

 public function getNews($slug = false)
 {
  if ($slug === false) {
   return $this->findAll();
  }

  return $this->asArray()
   ->where(['slug' => $slug])
   ->first();
 }
}

这里是控制器(News.php)

<?php

namespace App\Controllers;

use App\Models\NewsModel;
use CodeIgniter\Controller;

class News extends Controller
{
 public function index()
 {
  $model = new NewsModel();

  $data = [
   'news' => $model->getNews(),
   'title' => 'News archive',
  ];

  echo view('templates/header', $data);
  echo view('news/overview', $data);
  echo view('templates/footer', $data);
 }

 public function view($slug = null)
 {
  $model = new NewsModel();

  $data['news'] = $model->getNews($slug);

  if (empty($data['news'])) {
   throw new \CodeIgniter\Exceptions\PageNotFoundException('Cannot find the news item: ' . $slug);
  }

  $data['title'] = $data['news']['title'];

  echo view('templates/header', $data);
  echo view('news/view', $data);
  echo view('templates/footer', $data);
 }
 public function create()
 {
  $model = new NewsModel();

  if ($this->request->getMethod() === 'post' && $this->validate([
   'title' => 'required|min_length[3]|max_length[255]',
   'body' => 'required',
  ])) {
   $model->save([
    'title' => $this->request->getPost('title'),
    'slug' => url_title($this->request->getPost('title'), '-', true),
    'body' => $this->request->getPost('body'),
   ]);

   echo view('news/success');

  } else {
   echo view('templates/header', ['title' => 'Create a news item']);
   echo view('news/create');
   echo view('templates/footer');
  }
 }
}

查看(view.php)

<h2><?=esc($news['title'])?></h2>
<p><?=esc($news['body'])?></p>



<button><a href="/news/delete" class="btn btn-danger">Delete</a></button>

我已经在我的控制器中尝试了以下操作

它并没有从我的数据库中删除它,但我也没有收到错误!它只是将我重定向到我的成功页面。

public function delete($id = null)
{
$model = new NewsModel();

$model->delete([
 $model->where('id', $id)->delete(),
]);

return view('news/delete');
}

我也试过这个

   public function delete()
 {
  $model = new NewsModel();

  if ($this->request->getMethod() === 'post') {
   $model->delete([
    'title' => $this->request->getPost('title'),  
    'body' => $this->request->getPost('body'),
   ]);
   echo view('news/delete');
  }
 

数据库设置

DB NAME= toets
TABLE= news
id|title|slug|body

我将我的视图按钮更改为

<a href="<?= '/news/delete/' . esc($news['id']) ?>">Delete</a>

在我的控制器中我制作了

 public function delete($id)
{
    $model = new NewsModel();
    $model->where('id', (int) $id)->delete();

    return view('news/delete');
}