m180513_085059_drop_media_stats_table::safeDown()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 31
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 21
nc 2
nop 0
dl 0
loc 31
rs 9.584
c 1
b 0
f 0
1
<?php
2
3
use yii\db\Migration;
4
5
/**
6
 * Handles the dropping of table `media_stats`.
7
 */
8
class m180513_085059_drop_media_stats_table extends Migration
9
{
10
    /**
11
     * {@inheritdoc}
12
     */
13
    public function safeUp()
14
    {
15
        $this->addColumn('media', 'likes', $this->integer());
16
        $this->addColumn('media', 'comments', $this->integer());
17
        $this->addColumn('media', 'account_followed_by', $this->integer());
18
        $this->addColumn('media', 'account_follows', $this->integer());
19
20
        $sql = 'SELECT * FROM media_stats WHERE id IN (SELECT MAX(id) FROM media_stats GROUP BY media_id)';
21
        $rows = Yii::$app->db->createCommand($sql)
22
            ->queryAll();
23
24
        foreach ($rows as $row) {
25
            $this->update('media', [
26
                'likes' => $row['likes'],
27
                'comments' => $row['comments'],
28
                'account_followed_by' => $row['comments'],
29
                'account_follows' => $row['account_follows'],
30
            ], ['id' => $row['media_id']]);
31
        }
32
33
        $this->dropForeignKey('fk_media_stats_media', 'media_stats');
34
        $this->dropTable('media_stats');
35
    }
36
37
    /**
38
     * {@inheritdoc}
39
     */
40
    public function safeDown()
41
    {
42
43
        $this->createTable('media_stats', [
44
            'id' => $this->primaryKey(),
45
            'likes' => $this->integer(),
46
            'comments' => $this->integer(),
47
            'account_followed_by' => $this->integer(),
48
            'account_follows' => $this->integer(),
49
            'media_id' => $this->integer(),
50
        ]);
51
52
        $this->addForeignKey('fk_media_stats_media', 'media_stats', 'media_id', 'media', 'id', 'CASCADE');
53
54
        $rows = Yii::$app->db->createCommand('SELECT * FROM media')
55
            ->queryAll();
56
57
        foreach ($rows as $row) {
58
            $this->insert('media_stats', [
59
                'likes' => $row['likes'],
60
                'comments' => $row['comments'],
61
                'account_followed_by' => $row['account_followed_by'],
62
                'account_follows' => $row['account_follows'],
63
                'media_id' => $row['id'],
64
            ]);
65
        }
66
67
        $this->dropColumn('media', 'likes');
68
        $this->dropColumn('media', 'comments');
69
        $this->dropColumn('media', 'account_followed_by');
70
        $this->dropColumn('media', 'account_follows');
71
    }
72
}
73