我對 Laravel 和 Eloquent 還很陌生,但加入了一個以前建立的專案。
我有一個用戶模型,它有很多關系,例如 Actions(HasMany)、Roles(BelongsToMany)、Type(BelongsTo) 等等......
我想要做的是洗掉一個用戶模型及其資料,當我這樣做時,洗掉他關系中的所有痕跡,而不是內容本身,基本上我想保留他的關系模型(動作、角色、型別,...) 在我的資料庫中,但洗掉了他的 FK,以便它不能再鏈接到我的用戶,同時保持以前與他關聯的條目。
我嘗試了一些沒有成功的事情,比如
$user = User::findOrFail($id)
$user->delete();
// This one giving me a SQLSTATE[23000] The DELETE statement conflicted with the REFERENCE constraint
$user->actions()->detach()
// or
$user->actions()->dissociate()
// But undefined for HasMany relations
我想知道除了在每個關系中將所有這些 Foreign_Keys 更新為“NULL”值之外,是否有一種“干凈”且簡單的方法來做到這一點
$user->userActions()->update(['id_user' => null]);
$user->userRoles()->update(['id_user' => null]);
//...and on and on... before being able to do a
$user->delete();
我希望我足夠清楚。
謝謝。
uj5u.com熱心網友回復:
如果您使用硬洗掉,我建議使用 ondelete set null :
Schema::table('roles', function (Blueprint $table) {
$table->unsignedInteger('id_user')->nullable();
$table->foreign('id_user')->references('id')->on('users')->onDelete('set null');
});
Schema::table('actions', function (Blueprint $table) {
$table->unsignedInteger('id_user')->nullable();
$table->foreign('id_user')->references('id')->on('users')->onDelete('set null');
});
無需模型事件或自己管理,mysql為您管理一切
uj5u.com熱心網友回復:
您必須先洗掉所有相關記錄,然后再洗掉記錄本身:
$user = User::findOrFail($id);
$user->actions()->detach();
$user->delete();
或者您可以注冊在調度各種模型事件時執行的閉包。通常,您應該在模型的 booted 方法中注冊這些閉包:
<?php
namespace App\Models;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
protected static function booted()
{
static::deleting(function ($user) {
$user->actions()->detach();
});
}
}
參考
uj5u.com熱心網友回復:
您可以將用戶洗掉為:
$user = User::findOrFail($id)
$user->delete();
這里的問題是,您不想洗掉其他表中用戶的所有資訊。在 SQL 中,您專門為此目的定義了外鍵,因此您在表中沒有“丟失在空間中”的資料,因為它與任何東西都不相關。這會構建(空間)具有難以訪問的資訊的表,因為它與任何內容無關。
為此,人們通常使用“ ON DELETE CASCADE ”來洗掉其他表中的所有參考(由 FK 相關)。如果你沒有這個,你必須在洗掉用戶之前手動洗掉其他表中的資訊。
我的建議是重新考慮為什么要洗掉用戶并保留資料,如果要保留資料只是禁用用戶,最終您將想知道其他用戶的資料的用戶資訊表。
我希望這可以幫助并澄清您的問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/487860.html
