--- /dev/null
+<?php
+
+use yii\db\Migration;
+
+/**
+ * Handles adding order column to table `{{%matrix_erp_media}}`.
+ */
+class m251003_120000_add_order_column_to_matrix_erp_media extends Migration
+{
+ /**
+ * {@inheritdoc}
+ */
+ const TABLE_NAME = 'erp24.matrix_erp_media';
+
+ /**
+ * {@inheritdoc}
+ */
+ public function safeUp()
+ {
+ $tableSchema = $this->db->getTableSchema(self::TABLE_NAME);
+
+ if (isset($tableSchema)) {
+ $this->addColumn(self::TABLE_NAME, 'foto_order', $this->integer()->defaultValue(1)->after('updated_at'));
+
+ // Заполняем поле order существующими данными по порядку id для каждого guid
+ // Используем оконную функцию PostgreSQL
+ $this->execute("
+ UPDATE " . self::TABLE_NAME . "
+ SET foto_order = sub.row_number
+ FROM (
+ SELECT id,
+ ROW_NUMBER() OVER (PARTITION BY guid ORDER BY id) as row_number
+ FROM " . self::TABLE_NAME . "
+ ) sub
+ WHERE " . self::TABLE_NAME . ".id = sub.id
+ ");
+ }
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function safeDown()
+ {
+ $tableSchema = $this->db->getTableSchema(self::TABLE_NAME);
+ if (isset($tableSchema) && isset($tableSchema->columns['foto_order'])) {
+ $this->dropColumn(self::TABLE_NAME, 'foto_order');
+ }
+ }
+}