Laravel中的SQL Server ON DELETE CASCADE错误 [英] SQL Server ON DELETE CASCADE Error In Laravel
问题描述
我正在使用Laravel Framework;我有多个连接的表,
I'm using Laravel Framework; I have multiple connected tables,
用户模式表:
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
文章模式表:
Schema::create('articles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->string("title");
$table->string("slug")->unique();
$table->text("cover");
$table->text("body");
$table->boolean("status")->default(1);
$table->timestamps();
});
注释模式表:
Schema::create('comments', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger("user_id");
$table->foreign("user_id")->references("id")->on("users")->onDelete('cascade');
$table->unsignedBigInteger("article_id");
$table->foreign("article_id")->references("id")->on("articles")->onDelete('cascade');
$table->text("comment");
$table->bigInteger("level");
$table->boolean("status")->default(0);
$table->timestamps();
});
在注释表中,我有以下重要代码:
In the comments table I have this important code:
$table->unsignedBigInteger("user_id");
$table->foreign("user_id")->references("id")->on("users")->onDelete('cascade');
$table->unsignedBigInteger("article_id");
$table->foreign("article_id")->references("id")->on("articles")->onDelete('cascade');
我想在删除文章或用户时希望在删除用户或文章时删除其注释,但这是SQL Server数据库中的错误.
I want to when I delete an article or user, I would like to have their comments deleted when a user or an article is deleted, But this is a mistake in the SQL Server database.
错误表SQL Server数据库:在此处输入图片描述
当我删除此方法时
-> onDelete('cascade');
->onDelete('cascade');
错误消失.
我绝对需要相应的方法.谁能指导我解决这个问题?
I definitely need to have the corresponding method. Can anyone guide me to solve this problem?
推荐答案
使用删除观察器代替,删除级联上的
不是最好的选择.
Use a delete observer instead, on delete cascade
is not the best thing to do.
在 User
模型中定义关系:
/**
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function articles()
{
return $this->hasMany(Article::class, 'user_id');
}
然后实施 boot
方法以观察记录的删除
Then implement the boot
method to observe the deletion of a record
protected static function boot() {
parent::boot();
static::deleting(function($user) {
$user->articles()->delete();
});
}
您可以使用相同的方法循环文章注释,或者使用 Article
和 Comment
模型
You can loop on articles comments in the same method or do the same thing you did here with Article
and Comment
models
在此处了解有关观察者的更多信息 https://laravel.com/docs/5.8/eloquent#观察者
Read more about observers here https://laravel.com/docs/5.8/eloquent#observers
这篇关于Laravel中的SQL Server ON DELETE CASCADE错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!