-
Notifications
You must be signed in to change notification settings - Fork 635
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add foreign key to addresses fieldId column + gc adjustment
- Loading branch information
Showing
3 changed files
with
60 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
57 changes: 57 additions & 0 deletions
57
src/migrations/m240906_115231_add_addresses_fieldid_fk_constraint.php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
<?php | ||
|
||
namespace craft\migrations; | ||
|
||
use craft\db\Migration; | ||
use craft\db\Table; | ||
|
||
/** | ||
* m240906_115231_add_addresses_fieldid_fk_constraint migration. | ||
*/ | ||
class m240906_115231_add_addresses_fieldid_fk_constraint extends Migration | ||
{ | ||
/** | ||
* @inheritdoc | ||
*/ | ||
public function safeUp(): bool | ||
{ | ||
// first clean up addresses that already belong to fields that were hard deleted | ||
$addressesTable = Table::ADDRESSES; | ||
$fieldsTable = Table::FIELDS; | ||
|
||
if ($this->db->getIsMysql()) { | ||
$sql = <<<SQL | ||
DELETE [[a]].* FROM $addressesTable [[a]] | ||
LEFT JOIN $fieldsTable [[f]] ON [[f.id]] = [[a.fieldId]] | ||
WHERE [[a.fieldId]] IS NOT NULL AND | ||
[[f.id]] IS NULL | ||
SQL; | ||
} else { | ||
$sql = <<<SQL | ||
DELETE FROM $addressesTable | ||
USING $addressesTable [[a]] | ||
LEFT JOIN $fieldsTable [[f]] ON [[f.id]] = [[a.fieldId]] | ||
WHERE | ||
$addressesTable.[[id]] = [[a.id]] AND | ||
[[a.fieldId]] IS NOT NULL AND | ||
[[f.id]] IS NULL | ||
SQL; | ||
} | ||
|
||
$this->db->createCommand($sql)->execute(); | ||
|
||
// and now add a foreign key | ||
$this->addForeignKey(null, Table::ADDRESSES, ['fieldId'], Table::FIELDS, ['id'], 'CASCADE', null); | ||
|
||
return true; | ||
} | ||
|
||
/** | ||
* @inheritdoc | ||
*/ | ||
public function safeDown(): bool | ||
{ | ||
echo "m240906_115231_add_addresses_fieldid_fk_constraint cannot be reverted.\n"; | ||
return false; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters