-
Notifications
You must be signed in to change notification settings - Fork 4
/
DbHelper.php
74 lines (67 loc) · 1.96 KB
/
DbHelper.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<?php
/**
* DbHelper class file.
* @license http://www.opensource.org/licenses/bsd-license.php
*/
/**
* Helper for migration commands.
*
* @author Pavel Bariev <[email protected]>
*/
namespace bariew\moduleMigration;
use Yii;
use yii\db\Command;
class DbHelper
{
/**
* Disables foreign key check. Use it before table migration operations.
* @return int whether check is disabled.
*/
public static function foreignKeysOff()
{
return Yii::$app->db->createCommand("SET foreign_key_checks = 0")->execute();
}
/**
* Enables foreign key check. Use it after table migration operations.
* @return int whether check is enabled.
*/
public static function foreignKeysOn()
{
return Yii::$app->db->createCommand("SET foreign_key_checks = 1")->execute();
}
/**
* Inserts new data into table or updates on duplicate key.
* @param string $tableName db table name
* @param array $columns db column names
* @param array $data data to insert
* @param string $db application connection name
* @return Command the DB command
*/
public static function insertUpdate($tableName, $columns, $data, $db = 'db')
{
if (!$data) {
return false;
}
foreach ($data as $key => $row) {
$data[$key] = array_values($row);
}
$sql = \Yii::$app->$db->createCommand()->batchInsert($tableName, $columns, $data)->rawSql;
$sql .= 'ON DUPLICATE KEY UPDATE ';
$values = [];
foreach ($columns as $column) {
$values[] = "{$column} = VALUES({$column})";
}
$sql .= implode($values, ', ');
return \Yii::$app->$db->createCommand($sql);
}
/**
* Extracts column names from table data.
* @param array $data table data.
* @return array column names.
*/
public static function dataColumns($data)
{
$row = reset($data);
return array_keys($row);
}
}