Craft content migrations: update the row, not the element
Twice this year I had to apply an accessibility audit to a Craft site: a spreadsheet of asset IDs and the alt text each image should have, thousands of rows, and a request to get it into the database in a way that replays on every environment. A content migration is the right tool for that. What I put inside the migration changed a lot between the first time and the second, and the second version is the one I would write again.
The short version: use a single database transaction with direct updates instead of saving each element through Craft. It has fewer cascading effects, and it will not take the database down with it.
The first version
The March migration did what every Craft tutorial does. Fetch the data, loop, save the element.
public function safeUp(): bool
{
$csv = file_get_contents(self::CSV_URL);
$rows = array_map('str_getcsv', explode("\n", $csv));
array_shift($rows);
foreach ($rows as $row) {
$asset = Asset::find()->id(trim($row[0]))->status(null)->one();
if (! $asset) {
continue;
}
$asset->setFieldValue('altText', trim($row[4]));
Craft::$app->elements->saveElement($asset);
}
return true;
}
It worked on the sandbox, it got merged, and it is the version I now hold up as the wrong shape. Two things are wrong with it.
Every row is an element save. saveElement() is not an update. It validates, fires the before-save and after-save events, writes the element row, writes the content row, rewrites relations, rebuilds the search index for that element, propagates to every site the asset lives in, and lets every installed plugin react. That is the right amount of work when an editor saves one image in the control panel. Multiplied by a few thousand rows inside a deploy, it is thousands of events and tens of thousands of queries, all holding locks on the content, elements, relations, and search tables while the live site is trying to use them. The transaction that safeUp() wraps around all of it does not help here. It makes the lock last longer.
The data lives at a URL. The migration fetched its CSV from a bucket at run time. That means the deploy has a network dependency, the file can change or disappear between environments, and six months later nobody can say what the migration actually wrote. A migration should be reproducible from the repository alone.
The second version
In September the same audit came around for another site, with 6,376 assets. This is the migration I wrote instead, trimmed:
public function safeUp(): bool
{
$siteId = Craft::$app->getSites()->getPrimarySite()->id;
$alt = $this->data(); // assetId => altText, embedded in this file
$existing = (new Query())
->select(['elementId'])
->from(['{{%content}}'])
->where(['siteId' => $siteId, 'elementId' => array_keys($alt)])
->column();
$existing = array_flip(array_map('intval', $existing));
$db = Craft::$app->getDb();
$transaction = $db->beginTransaction();
try {
foreach ($alt as $id => $value) {
if (! isset($existing[$id])) {
continue;
}
$db->createCommand()
->update('{{%content}}', ['field_altText' => $value], ['elementId' => $id, 'siteId' => $siteId])
->execute();
}
$transaction->commit();
} catch (\Throwable $e) {
$transaction->rollBack();
$this->log('Rolled back, no changes applied: '.$e->getMessage());
return false;
}
Craft::$app->getCache()->flush();
return true;
}
The differences are the whole lesson.
One column, one site, one query per row. The templates read image.altText, which is the custom field stored in content.field_altText, not the native assets.alt column. So that is the only column the migration touches, on the primary site only, and the second-language site keeps falling back to the image title the way it always has. No events fire. Nothing propagates. Nothing is re-indexed. The 6,376 updates ran in about half a second against a copy of production.
The data is in the file. The audit ships as a PHP array returned from a private method at the bottom of the migration. The file is big and ugly and that is fine. Anyone can open it in a year and read exactly what was written to which asset.
Check what exists first, then do all of it or none of it. One query up front tells me which asset IDs actually have a content row on that site. The missing ones are logged and skipped instead of failing halfway through. Everything that does apply is inside an explicit transaction with a logged rollback. safeUp() already gives you an outer transaction, but opening my own makes the boundary visible in the code and gives me somewhere to put the message that tells the next person nothing was applied.
Flush once. The front end is served from a static cache, so the migration flushes it once at the end rather than relying on per-element invalidation firing thousands of times.
What you give up
Direct updates skip the search index on purpose. If the alt text needs to be searchable in the control panel, that is a one-liner after deploy:
craft resave/assets --update-search-index
I would rather run that once, deliberately, than have the migration do it implicitly for every row while the site is up.
The other thing you give up is a reversible migration. The first version re-fetched the CSV and wrote the old values back in safeDown(). The second says it cannot be reverted and returns false. That is more honest. Reverting an audit means re-applying the previous audit, and the previous audit is a separate migration.
Where this does not apply
This is about bulk work with a known shape. If a migration needs to save ten entries and the side effects are the point, like regenerating slugs or triggering a plugin, save the elements. The element service is the right tool when you want everything it does. For thousands of rows of a single field, you do not want everything it does. You want the row updated.