74 lines
2.1 KiB
PHP
74 lines
2.1 KiB
PHP
<?php
|
|
|
|
namespace App\Database\Migrations;
|
|
|
|
use CodeIgniter\Database\Migration;
|
|
|
|
class RevertPrintRequestsForeignKey extends Migration
|
|
{
|
|
public function up()
|
|
{
|
|
if (! $this->db->tableExists('print_requests')) {
|
|
return;
|
|
}
|
|
|
|
// Drop the old foreign key if it exists
|
|
$db = \Config\Database::connect();
|
|
$keys = $db->getForeignKeyData('print_requests');
|
|
foreach ($keys as $key) {
|
|
if ($key->constraint_name === 'print_requests_class_id_foreign') {
|
|
try {
|
|
$this->forge->dropForeignKey('print_requests', 'print_requests_class_id_foreign');
|
|
} catch (\Throwable $e) {
|
|
// Already absent.
|
|
}
|
|
break;
|
|
}
|
|
}
|
|
|
|
if (! $this->db->tableExists('classes')) {
|
|
return;
|
|
}
|
|
|
|
$orphanCount = (int) $db->table('print_requests pr')
|
|
->join('classes c', 'c.id = pr.class_id', 'left')
|
|
->where('pr.class_id IS NOT NULL', null, false)
|
|
->where('c.id IS NULL', null, false)
|
|
->countAllResults();
|
|
|
|
if ($orphanCount > 0) {
|
|
return;
|
|
}
|
|
|
|
// Add the new foreign key
|
|
$this->forge->addForeignKey('class_id', 'classes', 'id', 'CASCADE', 'CASCADE');
|
|
|
|
// Process the modifications
|
|
$this->forge->processIndexes('print_requests');
|
|
}
|
|
|
|
public function down()
|
|
{
|
|
if (! $this->db->tableExists('print_requests')) {
|
|
return;
|
|
}
|
|
|
|
// Drop the new foreign key
|
|
try {
|
|
$this->forge->dropForeignKey('print_requests', 'print_requests_class_id_foreign');
|
|
} catch (\Throwable $e) {
|
|
// Already absent.
|
|
}
|
|
|
|
if (! $this->db->tableExists('class_sections')) {
|
|
return;
|
|
}
|
|
|
|
// Re-add the old foreign key
|
|
$this->forge->addForeignKey('class_id', 'class_sections', 'id', 'CASCADE', 'CASCADE');
|
|
|
|
// Process the modifications
|
|
$this->forge->processIndexes('print_requests');
|
|
}
|
|
}
|