温馨提示×

Linux系统下Laravel数据库如何管理

小樊
54
2025-09-18 17:54:54
栏目: 智能运维

Linux系统下Laravel数据库管理指南

一、数据库环境配置

1. 安装数据库服务器

Linux系统下常用MySQL或PostgreSQL作为Laravel的数据库后端。以MySQL为例,安装步骤如下(以CentOS为例):

sudo yum install mysql-server # 安装MySQL服务器 sudo systemctl start mysqld # 启动MySQL服务 sudo systemctl enable mysqld # 设置开机自启 sudo mysql_secure_installation # 运行安全脚本,设置root密码并删除匿名用户 

若使用PostgreSQL,命令类似:

sudo yum install postgresql-server postgresql-contrib # 安装PostgreSQL sudo systemctl start postgresql # 启动服务 sudo systemctl enable postgresql # 开机自启 

2. 创建数据库与用户

登录数据库(MySQL示例):

mysql -u root -p # 输入root密码登录 

执行以下SQL创建数据库和用户(替换laravel_dblaravel_useryour_password为实际值):

CREATE DATABASE laravel_db CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; -- 创建数据库(指定字符集) CREATE USER 'laravel_user'@'localhost' IDENTIFIED BY 'your_password'; -- 创建用户 GRANT ALL PRIVILEGES ON laravel_db.* TO 'laravel_user'@'localhost'; -- 授权 FLUSH PRIVILEGES; -- 刷新权限 EXIT; -- 退出 

3. 配置Laravel连接

修改Laravel项目根目录下的.env文件,调整数据库连接参数:

DB_CONNECTION=mysql # 数据库驱动(MySQL/PostgreSQL/SQLite等) DB_HOST=127.0.0.1 # 数据库服务器地址(本地为127.0.0.1) DB_PORT=3306 # 数据库端口(MySQL默认3306,PostgreSQL默认5432) DB_DATABASE=laravel_db # 数据库名 DB_USERNAME=laravel_user # 数据库用户名 DB_PASSWORD=your_password # 数据库密码 

4. 测试连接

创建测试路由(routes/web.php)验证连接:

Route::get('/test-db', function () { $users = DB::table('users')->get(); // 查询users表(需存在) return view('welcome', compact('users')); }); 

访问http://your-server-ip/test-db,若能显示数据则配置成功。

二、数据库迁移管理

迁移是Laravel管理数据库结构变更的核心工具,支持版本控制与团队协作。

1. 创建迁移文件

使用Artisan命令生成迁移文件,指定表名(如users):

php artisan make:migration create_users_table --create=users # 创建新表 php artisan make:migration add_votes_to_users_table --table=users # 给现有表添加字段 

迁移文件会保存在database/migrations目录下,文件名包含时间戳(如2025_09_18_000000_create_users_table.php)。

2. 编辑迁移文件

打开生成的迁移文件,修改up(创建/修改结构)和down(回滚操作)方法。例如,创建users表的迁移:

use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateUsersTable extends Migration { public function up() { Schema::create('users', function (Blueprint $table) { $table->id(); // 自增主键 $table->string('name'); // 用户名 $table->string('email')->unique(); // 唯一邮箱 $table->timestamp('email_verified_at')->nullable(); // 邮箱验证时间 $table->string('password'); // 密码 $table->rememberToken(); // 记住我token $table->timestamps(); // 创建/更新时间 }); } public function down() { Schema::dropIfExists('users'); // 回滚时删除表 } } 

3. 运行迁移

执行以下命令应用所有未完成的迁移:

php artisan migrate 

若需强制在生产环境运行(可能丢失数据),添加--force参数:

php artisan migrate --force 

4. 回滚与重建

  • 回滚最后一次迁移:
    php artisan migrate:rollback 
  • 回滚最近5次迁移:
    php artisan migrate:rollback --step=5 
  • 重建数据库(删除所有表并重新运行迁移):
    php artisan migrate:refresh # 仅重建 php artisan migrate:refresh --seed # 重建并填充种子数据 

三、数据库种子管理

种子用于填充测试或演示数据,提升开发效率。

1. 创建种子类

使用Artisan生成种子文件(如UsersTableSeeder):

php artisan make:seeder UsersTableSeeder 

种子文件会保存在database/seeds目录下。

2. 编写种子逻辑

打开种子文件,编辑run方法,使用DB门面或Eloquent插入数据。例如:

use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB; class UsersTableSeeder extends Seeder { public function run() { DB::table('users')->insert([ 'name' => 'John Doe', 'email' => 'john@example.com', 'password' => bcrypt('password'), // 密码加密 'created_at' => now(), 'updated_at' => now(), ]); } } 

3. 关联模型工厂(可选)

若需生成大量随机数据,可使用模型工厂。首先创建工厂:

php artisan make:factory UserFactory --model=User 

编辑database/factories/UserFactory.php,定义数据生成规则:

use Faker\Generator as Faker; $factory->define(App\Models\User::class, function (Faker $faker) { return [ 'name' => $faker->name, 'email' => $faker->unique()->safeEmail, 'password' => bcrypt('password'), 'created_at' => now(), 'updated_at' => now(), ]; }); 

修改种子文件,使用工厂生成50条数据:

use App\Models\User; public function run() { User::factory()->count(50)->create(); // 生成50条用户数据 } 

4. 执行种子

  • 运行所有种子(DatabaseSeeder.php中定义的种子类):
    php artisan db:seed 
  • 单独运行某个种子类:
    php artisan db:seed --class=UsersTableSeeder 

四、常见问题排查

  1. 连接失败:检查.env中的数据库配置是否正确,数据库服务是否启动,防火墙是否允许端口通信(如MySQL的3306端口)。
  2. 迁移冲突:若迁移文件已执行但结构有误,可修改down方法确保回滚正确,再重新运行迁移。
  3. 种子重复:避免多次运行同一种子导致数据重复,可在run方法中添加判断逻辑(如检查数据是否存在)。

通过以上步骤,可在Linux系统下高效管理Laravel数据库,实现结构变更的版本控制与测试数据的快速填充。

0