php - 删除()或强制删除()。更好的确定方法
问题描述
我有一个包含 95 个表的数据库。users
存在系统用户的表。许多其他表(95 个中的 45 个)都有一个“created_by”,它指的是创建/添加行的用户,通过users.id
.
现在。如果我想删除一个用户,我不能去做$user->delete()
,我需要保留用户(软删除它),以防这个用户在其他表上创建了行。但是如果这个用户没有添加任何内容,那么我应该继续进行$user->forceDelete()
。
我的问题是:有没有一个好的方法可以做到这一点?当我们有这么多的表时,检查是否应该删除或强制删除用户。
我想我可以遍历表并检查用户的 id(要删除)是否存在,如果找到则它是 ->delete(),否则它是 ->forceDelete()。这是代码:
// Get all tables
$allTables = \DB::connection()->getDoctrineSchemaManager()->listTableNames();
$tablesWithCreatedBy = [];
foreach($allTables as $tableName){
$tableColumns = \DB::getSchemaBuilder()->getColumnListing($tableName);
if(in_array('created_by', $tableColumns)){
$tablesWithCreatedBy[] = $tableName;
}
}
foreach($tablesWithCreatedBy as $tableName){
$result = \DB::select(" SELECT created_by FROM `$tableName`
WHERE `created_by` = {$this->user->id} LIMIT 0, 1 ");
if(isset($result[0])){
$this->user->delete();
break;
}
}
// If wasn't trashed from the code above, then force delete the user!
if(!$this->user->trashed()){
$this->user->forceDelete();
}
我觉得必须有更好的方法来做到这一点!在那儿?
解决方案
您必须添加records_count
到users
每次用户将内容添加到其他表时都会递增的表,因此在该更改解决方案之后将很简单:
$result = ($this->user->records_count > 0)
? $this->user->delete()
: $this->user->forceDelete();
或者编写 Laravel 控制台命令并在后台运行它,它将遍历 db 并执行清理操作。
推荐阅读
- javascript - 在角度 5 中验证表格内的输入文本用户输入
- spring-boot - Springboot中的流程指标没有出现
- spring-boot - 如何决定微服务的数量以及是否有通用的jar
- reactjs - 反应 | http-proxy-middleware 包不工作
- facebook - 如何将沙盒广告帐户添加到 BusinessManager?
- artifactory - Artifactory 自定义基本 URL 给出 404 页面未找到错误
- r - 我可以双击 visNetwork 图中的节点来运行函数吗?
- phpstorm - PhpStorm 不换行
- quickjs - quickJS 文档和/或评论良好的项目
- python - python的长文本中的特定单词搜索