funayaki / cakephp3-soft-delete
CakePHP 的 SoftDelete 插件
2.0.0
2018-08-30 07:53 UTC
Requires
- php: >=5.4
- cakephp/cakephp: ~3.0
- cakephp/plugin-installer: *
Requires (Dev)
- phpunit/phpunit: ^5.7|^6.0
README
目的
此 CakePHP 插件允许您使模型支持软删除。当软删除一个实体时,它实际上不会被从数据库中删除。相反,记录上设置了一个 deleted
时间戳。
要求
- CakePHP 3.5.0 或更高版本
安装
您可以使用 composer 将此插件安装到您的 CakePHP 应用程序中。
更新您的 composer 文件以包含此插件
composer require funayaki/cakephp3-soft-delete
配置
加载插件
// In /config/bootstrap.php Plugin::load('SoftDelete');
使模型支持软删除
在您的模型 Table 类上使用 SoftDeleteTrait
并实现 SoftDeleteAwareInterface
// in src/Model/Table/UsersTable.php ... use SoftDelete\Model\Table\Entity\SoftDeleteAwareInterface; use SoftDelete\Model\Table\SoftDeleteTrait; class UsersTable extends Table implements SoftDeleteAwareInterface { use SoftDeleteTrait; public function getSoftDeleteField() { return 'deleted'; } public function getSoftDeleteValue() { return date('Y-m-d H:i:s'); } public function getRestoreValue() { return null; } }
使用
软删除记录
delete
和 deleteAll
函数现在将使用删除日期填充 deleted
字段来软删除记录。
// in src/Model/Table/UsersTable.php $this->delete($user); // $user entity is now soft deleted if UsersTable uses SoftDeleteTrait.
恢复软删除记录
要恢复一个软删除实体到活动状态,请使用 restore
方法
// in src/Model/Table/UsersTable.php // Let's suppose $user #1 is soft deleted. $user = $this->Users->find('all', ['withDeleted'])->where('id', 1)->first(); $this->restore($user); // $user #1 is now restored.
查找记录
find
、get
或动态查找器(如 findById
)将仅返回非软删除记录。要同时返回软删除记录,$options
必须包含 'withDeleted'
。示例
// in src/Model/Table/UsersTable.php $nonSoftDeletedRecords = $this->find('all'); $allRecords = $this->find('all', ['withDeleted']);
硬删除记录
要硬删除单个实体
// in src/Model/Table/UsersTable.php $user = $this->get($userId); $success = $this->hardDelete($user);
要批量硬删除在给定日期之前软删除的记录,可以使用 hardDeleteAll($date)
// in src/Model/Table/UsersTable.php $date = new \DateTime('some date'); $affectedRowsCount = $this->hardDeleteAll([ $this->getSoftDeleteField() . ' <=' => $date->format('Y-m-d H:i:s') ]);
软删除 & 关联
SoftDelete 插件正确处理关联。
- 软删除将按常规级联到相关模型。如果相关模型也使用 SoftDelete Trait,它们将被软删除。
- 软删除记录将被排除在计数器缓存之外。