Skip to content

Instantly share code, notes, and snippets.

@khalwat
Last active December 6, 2023 12:17
Show Gist options
  • Save khalwat/2df31a63d48428e2480e0ecf59ae316e to your computer and use it in GitHub Desktop.
Save khalwat/2df31a63d48428e2480e0ecf59ae316e to your computer and use it in GitHub Desktop.
Craft CMS content migration to add a database index to custom fields. Also has a `safeDown()` method to remove the indexes
<?php
namespace craft\contentmigrations;
use Craft;
use craft\db\Migration;
use craft\db\Table;
use craft\helpers\ElementHelper;
/**
* m231102_074933_add_index_to_demo_data migration.
*/
class m231102_074933_add_index_to_demo_data extends Migration
{
// The field handles we want to add database indexes for
public const FIELD_HANDLES = [
'demoData'
];
/**
* @inheritdoc
*/
public function safeUp(): bool
{
$fields = Craft::$app->getFields();
// Iterate through all of our fields by handle
foreach (self::FIELD_HANDLES as $fieldHandle) {
$field = $fields->getFieldByHandle($fieldHandle);
if ($field) {
// Find the column name the field uses in the content table
$column = ElementHelper::fieldColumnFromField($field);
if ($column) {
// Create an index for this field if it isn't already created
$this->createIndexIfMissing(Table::CONTENT, [$column], false);
}
}
}
return true;
}
/**
* @inheritdoc
*/
public function safeDown(): bool
{
$fields = Craft::$app->getFields();
// Iterate through all of our fields by handle
foreach (self::FIELD_HANDLES as $fieldHandle) {
$field = $fields->getFieldByHandle($fieldHandle);
if ($field) {
// Find the column name the field uses in the content table
$column = ElementHelper::fieldColumnFromField($field);
if ($column) {
// Delete the index for this field if it exists
$this->dropIndexIfExists(Table::CONTENT, [$column], false);
}
}
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment