php onDelete('cascade') 是什么意思?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43094543/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 02:46:05  来源:igfitidea点击:

What does onDelete('cascade') mean?

phplaravel

提问by code511788465541441

Schema::table('posts', function (Blueprint $table) {
    $table->integer('user_id')->unsigned();
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade')
});

Does this mean that if I delete a post, the user will also be deleted or does it mean if I delete a user, all their posts will be deleted?

这是否意味着如果我删除一个帖子,该用户也会被删除,或者是否意味着如果我删除一个用户,他们的所有帖子都会被删除?

回答by M.Elwan

Short answer is: in your case, if you deleted a user, all posts related to him will be deleted too.

简短的回答是:在你的情况下,如果你删除了一个user,所有与他相关的帖子也将被删除。

onDelete('cascade');simply adds ON DELETE CASCADErule to your database which specifies that the child data gets deleted when the parent data is deleted.

onDelete('cascade');只需ON DELETE CASCADE向您的数据库添加规则,该规则指定在删除父数据时删除子数据。

Note: take care of the typo (double semicolon)

注意:注意错别字(双分号)

$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

回答by Hyder B.

The code you are talking about creates a foreign key / reference to a column on another table. The onDelete('cascade')means that when the row is deleted, it will delete all it's references and attached data too.

您正在谈论的代码创建了对另一个表上列的外键/引用。这onDelete('cascade')意味着当该行被删除时,它也会删除它的所有引用和附加数据。

For example if you have a User which has a Post and you set onDelete('cascade') on the user, then when the user deletes his account, all posts will be deleted as well.

例如,如果您有一个拥有帖子的用户,并且您在用户上设置了 onDelete('cascade'),那么当用户删除他的帐户时,所有帖子也将被删除。

You can find more information on Laravel excellent documentation.

你可以在Laravel 优秀文档中找到更多信息。

回答by halloei

If you're using mysql, take a look at the documentation.

如果您使用的是 mysql,请查看文档

In your case it means: If the user is deleted, the post will also be deleted.

在您的情况下,这意味着:如果用户被删除,帖子也将被删除。

回答by Peter-Paul

It means that if you delete the 'user' linked, the 'posts' linked to that user will also automatically be deleted.

这意味着如果您删除链接的“用户”,链接到该用户的“帖子”也将自动删除。