CakePHP - 删除记录



要删除数据库中的记录,我们首先需要使用TableRegistry类获取表。我们可以使用get()方法从注册表中获取实例。get()方法将数据库表名作为参数。现在,这个新实例用于获取我们要删除的特定记录。

使用这个新实例调用get()方法并传递主键来查找记录,该记录将保存到另一个实例中。使用TableRegistry类的实例调用delete方法从数据库中删除记录。

示例

按照以下代码所示更改config/routes.php文件。

config/routes.php

<?php
use Cake\Http\Middleware\CsrfProtectionMiddleware;
use Cake\Routing\Route\DashedRoute;
use Cake\Routing\RouteBuilder;
$routes->setRouteClass(DashedRoute::class);
$routes->scope('/', function (RouteBuilder $builder) {
   $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([
      'httpOnly' => true,
   ]));
   $builder->applyMiddleware('csrf');
   //$builder->connect('/pages',['controller'=>'Pages','action'=>'display', 'home']);
   $builder->connect('/users/delete', ['controller' => 'Users', 'action' => 'delete']);
   $builder->fallbacks();
});

src/Controller/UsersController.php处创建一个UsersController.php文件。将以下代码复制到控制器文件中。

src/controller/UsersController.php

<?php
   namespace App\Controller;
   use App\Controller\AppController;
   use Cake\ORM\TableRegistry;
   use Cake\Datasource\ConnectionManager;
   class UsersController extends AppController{
      public function index(){
         $users = TableRegistry::get('users');
         $query = $users->find();
         $this->set('results',$query);
      }
      public function delete($id){
         $users_table = TableRegistry::get('users');
         $users = $users_table->get($id);
         $users_table->delete($users);
         echo "User deleted successfully.";
         $this->setAction('index');
      }
   }
?>

只需在Users目录下创建一个名为delete.ctp的空View文件。

src/Template/Users/delete.ctp

src/Template处创建一个Users目录(如果已创建则忽略),并在该目录下创建一个名为index.ctpView文件。将以下代码复制到该文件中。

src/Template/Users/index.ctp

<a href="add">Add User</a>
<table>
   <tr>
   <td>ID</td>
   <td>Username</td>
   <td>Password</td>
   <td>Edit</td>
   <td>Delete</td>
   </tr>
   <?php
      foreach ($results as $row):
      echo "<tr><td>".$row->id."</td>";
      echo "<td>".$row->username."</td>";
      echo "<td>".$row->password."</td>";
      echo "<td><a href='".$this->Url->build(["controller" => "Users","action" => "edit",$row->id])."'>Edit</a></td>";
      echo "<td><a href='".$this->Url->build(["controller" => "Users","action" => "delete",$row->id])."'>Delete</a></td></tr>";
      endforeach;
   ?>
</table>

通过访问以下URL并点击删除链接来执行上述示例以删除记录。

https://127.0.0.1:85/CakePHP/users

输出

访问上述URL并点击删除链接后,您将收到以下输出,您可以在其中删除记录。

Delete Link

点击删除链接删除记录。

User Deleted
广告