我正在开发一个 Laravel 应用程序,用于使用完整的管理仪表板管理案例研究,其中包括可登录系统的用户帐户的 CRUD 功能。
简而言之,一个case study和一个用户是一对多的关系(一个用户可以有多个case study,一个case study只能由一个用户创作);案例研究必须始终有创作它的用户。我遇到的问题是当我调用我的用户 Controller 上的 destroy 方法来删除用户时,它不起作用,因为数据库中有与该用户相关联的案例研究,我遇到了外键约束冲突.
我正在尝试找出解决此问题的最佳方法。我在想我可以创建一个名为“已删除用户”的用户来将案例研究分配给他们的作者被删除的时间。永远无法在数据库中删除或修改此“已删除用户”。您也将无法以“已删除用户”身份登录系统。
我不知道这是否会被视为一种不好的做法,而且我也认为我可能在可伸缩性方面存在问题。例如,如果一个用户有 5,000 个与之关联的案例研究并且该用户被删除,我怀疑更改数据库中的 5,000 行以附加“已删除用户”用户需要很长时间。
我也在使用 Sentinel 来管理不同级别的用户权限,因此当删除用户时,我还会将该用户从其在 role_users 数据透视表中的相应角色中分离出来。
我不知道它是否有帮助,但这是我在 UsersController 上的销毁函数:
public function destroy($id)
{
$user = User::findOrFail($id);
$user->delete();
$role = Sentinel::findById($id)->roles()->first();
$role->users()->detach($id);
Helpers::flash('The user has been successfully deleted.');
return redirect(route('admin.users.index'));
}
这是我的迁移:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('email');
$table->string('password');
$table->text('permissions')->nullable();
$table->timestamp('last_login')->nullable();
$table->string('first_name')->nullable();
$table->string('last_name')->nullable();
$table->rememberToken();
$table->timestamps();
$table->engine = 'InnoDB';
$table->unique('email');
});
Schema::create('studies', function (Blueprint $table) {
$table->increments('id');
$table->string('title', 150);
$table->string('problem');
$table->string('solution');
$table->string('analysis');
$table->string('slug');
$table->boolean('draft');
$table->integer('user_id')->unsigned();
$table->timestamps();
// Foreign key constraints
$table->foreign('user_id')->references('id')->on('users');
});
最佳答案
在你的 sentinel 的迁移文件中应该有 user_id
,它是 users
表的外键。
我假设您在所有列的底部都创建了外键约束。只需将它与 ->onDelete('cascade')
链接起来。如果删除用户,它将删除与该用户关联的所有案例研究。
您的外键代码应如下所示:
Schema::table('sentinels', function ($table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->.....
$table->.....
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('set null');
)};
Perform this before database migration. If already migrated run
php artisan migrate:rollback
on command line. Edit your migration file and again migrate your database running this code in command promptphp artisan migrate
关于mysql - 删除具有外键约束的用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34475212/