What does onDelete('cascade') mean?

后端 未结 4 1276
说谎
说谎 2021-02-02 10:00
Schema::table(\'posts\', function (Blueprint $table) {
    $table->integer(\'user_id\')->unsigned();
    $table->foreign(\'user_id\')->references(\'id\')->         


        
相关标签:
4条回答
  • 2021-02-02 10:36

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

    0 讨论(0)
  • 2021-02-02 10:41

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

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

    0 讨论(0)
  • 2021-02-02 10:49

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

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

    Note: take care of the typo (double semicolon)

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

    0 讨论(0)
  • 2021-02-02 10:53

    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.

    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.

    You can find more information on Laravel excellent documentation.

    0 讨论(0)
提交回复
热议问题