以下是在Linux环境下使用ThinkPHP进行数据库迁移的指南:
sudo apt update && sudo apt install apache2 mysql-server php php-mysql php-cli
curl -sS https://getcomposer.org/installer | php
sudo mv composer.phar /usr/local/bin/composer
/var/www/html
目录),并设置文件权限:sudo chown -R www-data:www-data /var/www/html/your_project
sudo chmod -R 755 /var/www/html/your_project
config/database.php
中配置数据库连接信息(如主机、用户名、密码、数据库名):return [
'type' => 'mysql',
'hostname' => 'localhost',
'database' => 'your_database',
'username' => 'root',
'password' => 'your_password',
'charset' => 'utf8mb4',
];
composer require topthink/think-migration
php think migrate:install
php think make:migration CreateUserTable
文件会生成在database/migrations
目录,文件名包含时间戳(如20250831100000_create_user_table.php
)。up()
和down()
方法定义表结构变更(推荐使用change()
方法,自动处理回滚逻辑):use think\migration\Migrator;
use think\migration\db\Column;
class CreateUserTable extends Migrator
{
public function change()
{
$table = $this->table('users');
$table->addColumn('username', 'string', ['limit' => 50])
->addColumn('email', 'string', ['limit' => 100, 'null' => true])
->addColumn('password', 'string', ['limit' => 255])
->addTimestamps()
->create();
}
}
php think migrate:run
php think migrate:rollback
php think make:seed UserSeeder
database/seeds
目录下编辑文件,定义插入数据逻辑:use think\migration\Seeder;
class UserSeeder extends Seeder
{
public function run()
{
$data = [
['username' => 'admin', 'email' => 'admin@example.com', 'password' => password_hash('123456', PASSWORD_DEFAULT)],
];
$this->table('users')->insert($data)->save();
}
}
php think seed:run
config/database.php
中的app_debug
参数)。参考资料: