freescout-restricted-customers/Database/Migrations/2024_07_10_162735_add_mailbox_id_column_to_customers_table.php

59 lines
1.9 KiB
PHP
Raw Normal View History

<?php
/*
2024-07-06 16:56:09 +00:00
SPDX-License-Identifier: AGPL-3.0-only
SPDX-FileCopyrightText: © 2024 Millions Missing FRANCE <info@millionsmissing.fr>
*/
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Symfony\Component\Console\Output\ConsoleOutput;
2024-07-10 15:26:43 +00:00
use Modules\MMFRestrictedCustomers\Entities\Customer;
class AddMailboxIdColumnToCustomersTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up() {
Schema::table('customers', function (Blueprint $table) {
// Add a "mailbox_id" field to the customers table, linking each customer entry to a specific mailbox.
$table
->integer('mailbox_id')
->unsigned()
// The column is nullable because entries without a linked mailbox might already exist.
->nullable();
$table
->foreign('mailbox_id')
->references('id')
->on('mailboxes')
// On mailbox deletion, delete all customer entries that are linked to it.
->onDelete('cascade');
});
// Link Customers to Mailboxes, through their Conversation information.
$output = new ConsoleOutput();
$output->writeln('<info>Linking existing Customers to Mailboxes, it might take a couple minutes…</info>');
$customers = Customer::all();
$customers->each(function ($customer) {
$customer->linkToMailboxThroughConversations();
});
$output->writeln('<info>Linking existing Customers to Mailboxes done.</info>');
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down() {
Schema::table('customers', function (Blueprint $table) {
// Delete all entries from the customers table that are linked to a specific mailbox.
Customer::has('mailbox')->delete();
// Delete the extra "mailbox_id" field from the customers table.
$table->dropForeign(['mailbox_id']);
$table->dropColumn('mailbox_id');
});
}
}