journal-intime/database/migrations/2020_03_17_084445_add_casca...

72 lines
2.8 KiB
PHP

<?php
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddCascadeOnTags extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
if (DB::getDriverName() !== 'sqlite') {
Schema::table('posts_tags', function (Blueprint $table) {
$table->dropForeign('post_id');
$table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade')->onUpdate('cascade');
$table->dropForeign('tag_id');
$table->foreign('tag_id')->references('id')->on('tags')->onDelete('cascade')->onUpdate('cascade');
});
} else {
// SQLite doesn't support drop foreign key
Schema::rename('posts_tags', 'post_tags_bu');
Schema::create('posts_tags', function (Blueprint $table) {
$table->bigIncrements('id');
$table->timestamps();
$table->bigInteger('post_id');
$table->bigInteger('tag_id');
$table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade')->onUpdate('cascade');
$table->foreign('tag_id')->references('id')->on('tags')->onDelete('cascade')->onUpdate('cascade');
});
DB::insert('insert into posts_tags (id, post_id, tag_id, created_at, updated_at)
select id, post_id, tag_id, created_at, updated_at from post_tags_bu');
Schema::drop('post_tags_bu');
}
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
if (DB::getDriverName() !== 'sqlite') {
Schema::table('posts_tags', function (Blueprint $table) {
$table->dropForeign('post_id');
$table->foreign('post_id')->references('id')->on('posts');
$table->dropForeign('tag_id');
$table->foreign('tag_id')->references('id')->on('tags');
});
} else {
// SQLite doesn't support drop foreign key
Schema::rename('posts_tags', 'post_tags_bu');
Schema::create('posts_tags', function (Blueprint $table) {
$table->bigIncrements('id');
$table->timestamps();
$table->bigInteger('post_id');
$table->bigInteger('tag_id');
$table->foreign('post_id')->references('id')->on('posts');
$table->foreign('tag_id')->references('id')->on('tags');
});
DB::insert('insert into posts_tags (id, post_id, tag_id, created_at, updated_at)
select id, post_id, tag_id, created_at, updated_at from post_tags_bu');
Schema::drop('post_tags_bu');
}
}
}