*/
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Symfony\Component\Console\Output\ConsoleOutput;
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('Linking existing Customers to Mailboxes, it might take a couple minutes…');
$customers = Customer::all();
$customers->each(function ($customer) {
$customer->linkToMailboxThroughConversations();
});
$output->writeln('Linking existing Customers to Mailboxes done.');
}
/**
* 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');
});
}
}