Cascade delete
https://laravelista.com/lessons/mysql-on-delete-cascade-or-set-null
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned()->index()->nullable();
$table->integer('category_id')->unsigned()->index() ;
$table->integer('photo_id')->unsigned()->index() ;
$table->string('title') ;
$table->text('body');
$table->timestamps();
/*
Delete User Content when deleting a user
reference the user ID on Users, cascade down and delete everything
If the 'User' of the post is deleted, delete all the posts that he has written".
------------------------------------------------------
id | user_id | category_id | photo_id | title | body |
--------|---------------------------------------------
|
______|
|
-V-------------------------------------------------
id | role_id | is_active | name | email | password
---------------------------------------------------
*/
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade') ;
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
}
=================== EXTRA =========================
after running the migration you will see the relationship at the end of the file
when you export the .sql file:
-- Constraints for table `tasks`
--
ALTER TABLE `tasks`
ADD CONSTRAINT `tasks_project_id_foreign` FOREIGN KEY (`project_id`) REFERENCES `projects` (`id`) ON DELETE CASCADE;
COMMIT;