首页 > 解决方案 > 删除()或强制删除()。更好的确定方法

问题描述

我有一个包含 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();
            }

我觉得必须有更好的方法来做到这一点!在那儿?

标签: phpmysqldatabaselaraveleloquent

解决方案


您必须添加records_countusers每次用户将内容添加到其他表时都会递增的表,因此在该更改解决方案之后将很简单:

$result = ($this->user->records_count > 0) 
          ? $this->user->delete() 
          : $this->user->forceDelete(); 

或者编写 Laravel 控制台命令并在后台运行它,它将遍历 db 并执行清理操作。


推荐阅读