-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDatabase.php
92 lines (84 loc) · 2.37 KB
/
Database.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<?php
/**
* Created by oiuv
* User: i@oiuv.cn
* Date: 2018-07-26
* Time: 21:40
*/
require __DIR__.'/vendor/autoload.php';
use Illuminate\Database\Capsule\Manager as DB;
class Database
{
// 运行迁移
public static function migrate()
{
$table = 'test_table';
// 判断数据表是否存在
if (DB::schema()->hasTable($table)) {
// 在已有数据表上创建字段
DB::schema()->table($table, function ($table) {
$table->string('mobile')->after('email');
});
} else {
// 创建数据表
DB::schema()->create($table, function ($table) {
$table->increments('id');
$table->string('email')->unique();
$table->timestamps();
});
}
}
// 回滚迁移
public static function rollback()
{
$table = 'test_table';
// 删除数据表
DB::schema()->dropIfExists($table);
// 删除数据表中的字段
if (DB::schema()->hasTable($table)) {
DB::schema()->table($table, function ($table) {
$table->dropColumn(['mobile']);
});
}
}
// 重命名数据表
public static function rename()
{
$table = 'test_table';
if (DB::schema()->hasTable($table))
DB::schema()->rename($table, 'test_demo');
}
// 升级数据库:4.2 → 5.0
public static function up()
{
// todo
}
// 降级数据库:5.0 → 4.2
public static function down()
{
// todo
}
}
if (isset($_GET['action']))
switch ($_GET['action']) {
case 'migrate':
try {
Database::migrate();
echo '数据库迁移成功';
} catch (PDOException $exception) {
echo $exception->getMessage();
}
break;
case 'rollback':
try {
Database::rollback();
echo '数据库滚回成功';
} catch (PDOException $exception) {
echo $exception->getMessage();
}
break;
default:
echo "没有数据库迁移操作";
}
else
echo "<a href='https://laravel-china.org/docs/laravel/5.6/migrations/1400#renaming-and-dropping-tables' target='_blank'>数据库迁移操作指南</a>";