forge->addField([ 'id' => ['type' => 'INT', 'unsigned' => true, 'auto_increment' => true], 'name' => ['type' => 'VARCHAR', 'constraint' => 100], ]); $this->forge->addKey('id', true); $this->forge->addUniqueKey('name'); $this->forge->createTable('specializations', true); $this->forge->addField([ 'id' => ['type' => 'INT', 'unsigned' => true, 'auto_increment' => true], 'doctor_id' => ['type' => 'INT', 'unsigned' => true], 'specialization_id' => ['type' => 'INT', 'unsigned' => true], ]); $this->forge->addKey('id', true); $this->forge->addKey('doctor_id'); $this->forge->addKey('specialization_id'); $this->forge->addUniqueKey(['doctor_id', 'specialization_id']); $this->forge->createTable('doctor_specializations', true); $db = \Config\Database::connect(); if (! $db->tableExists('doctors')) { return; } $doctors = $db->table('doctors') ->select('id, specialization') ->where('specialization IS NOT NULL') ->where('specialization !=', '') ->get() ->getResultArray(); foreach ($doctors as $doctor) { $rawNames = explode(',', (string) $doctor['specialization']); $names = []; foreach ($rawNames as $name) { $name = trim($name); if ($name !== '' && ! in_array($name, $names, true)) { $names[] = $name; } } foreach ($names as $name) { $existing = $db->table('specializations')->where('name', $name)->get()->getRowArray(); if ($existing) { $specializationId = (int) $existing['id']; } else { $db->table('specializations')->insert(['name' => $name]); $specializationId = (int) $db->insertID(); } $pivotExists = $db->table('doctor_specializations') ->where('doctor_id', (int) $doctor['id']) ->where('specialization_id', $specializationId) ->countAllResults() > 0; if (! $pivotExists) { $db->table('doctor_specializations')->insert([ 'doctor_id' => (int) $doctor['id'], 'specialization_id' => $specializationId, ]); } } } } public function down(): void { $this->forge->dropTable('doctor_specializations', true); $this->forge->dropTable('specializations', true); } }