Skip to content

第 2.2 章:创建 Planet 模型

学习时间: 45 分钟


1. Laravel 中的模型:宇宙对象的蓝图

在 MVC 架构(Model-View-Controller)中,模型 是:

  • 📦 数据的容器(行星参数)
  • 🔌 数据库操作接口
  • 🛡️ 应用程序业务逻辑的中心

💡 宇宙类比: Planet 模型 = 任务控制中心计算机中的行星蓝图。通过它可以:

  • 在目录中创建新行星 (INSERT)
  • 获取火星数据 (SELECT)
  • 更新大气层信息 (UPDATE)

2. 创建模型和迁移

Laravel 使用 Artisan CLI — 您的项目“控制台”。

步骤 1:生成带迁移的模型

php artisan make:model Planet -m

已创建文件:

app/
  └── Models/
      └── Planet.php    ← 模型
database/
  └── migrations/
      └── 2025_08_04_000000_create_planets_table.php  ← 迁移

Artisan 标志:

  • -m → 创建迁移
  • -c → 创建控制器
  • -r → 资源控制器

💡 专业提示: 这些标志可以组合使用以获得最大效率。命令 php artisan make:model Planet -mcr 将立即创建模型、迁移和用于管理该模型的资源控制器。这节省了大量时间。


3. 配置 Planet 模型

打开 app/Models/Planet.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Planet extends Model
{
    // 表名(默认为:'planets')
    // Laravel 默认假定表名是模型名的小写复数形式 (Planet -> planets)。
     // 因此,此处此属性并非必需,但有助于提高可读性。
    protected $table = 'planets';

    // 允许批量赋值的字段
    protected $fillable = [
        'name',
        'description',
        'size_km',
        'solar_system',
        'image_url'
    ];

    // 自动类型转换
    protected $casts = [
        'size_km' => 'integer'
    ];
}

属性说明:

属性 数据示例
$table 数据库中的表名 planets
$fillable 允许批量赋值的字段 name, size_km
$casts 自动类型转换 size_km: integer

4. 行星表设计

在编辑迁移文件之前,我们先定义“行星”的结构:

字段 数据类型 描述 示例值
id BIGINT (PK) 唯一 ID 1
name VARCHAR(255) 行星名称 "火星"
description TEXT 描述 "红色行星..."
size_km INTEGER 直径(公里) 6779
solar_system VARCHAR(100) 太阳系 "太阳系"
image_url VARCHAR(2048) 图片 URL(可为空) "https://..."
created_at TIMESTAMP 创建日期 2025-08-04 12:00:00
updated_at TIMESTAMP 更新日期 2025-08-05 09:30:00

5. 编辑迁移文件

打开 database/migrations/..._create_planets_table.php 中的迁移文件:

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreatePlanetsTable extends Migration
{
    public function up()
    {
        Schema::create('planets', function (Blueprint $table) {
            $table->id(); // BIGINT 自增

            $table->string('name')->unique();
            $table->text('description');
            $table->integer('size_km');
            $table->string('solar_system', 100);
            $table->string('image_url', 2048)->nullable();

            $table->timestamps(); // created_at + updated_at
        });
    }

    public function down()
    {
        Schema::dropIfExists('planets');
    }
}

要点:

  • ->unique() → 确保名称的唯一性
  • ->nullable() → 字段可以为空
  • timestamps() → 自动管理日期时间

6. 运行迁移(预览)

虽然迁移将在第 2.3 章中运行,但我们先看看它会是什么样子:

php artisan migrate

预期输出:

Migrating: 2025_08_04_000000_create_planets_table
Migrated:  2025_08_04_000000_create_planets_table (32.15ms)

在 pgAdmin 4 中检查:

  1. 打开 space_api 数据库 → Schemas → Tables
  2. 应该会出现 planets 表和您的字段

7. 替代方法:代码生成器

为了加速开发,可以使用以下包:

  • Laravel Blueprint - 根据 YAML 描述创建模型/迁移
  • InfyOm Laravel Generator - 基于数据库 schema 的生成器

Blueprint 示例:

models:
  Planet:
    name: string:255
    description: text
    size_km: integer
    solar_system: string:100
    image_url: string:2048? # '?' 符号表示字段可为空


巩固测验

1. 用于创建模型及其相关迁移的 Artisan 命令:

2. 模型中的 `$fillable` 属性用于

3. 迁移中的 `nullable()` 意味着:

4. 用于行星长描述的字段类型:

5. `timestamps()` 方法创建:


🚀 本章总结: 您已经创建了行星的“数字孪生”!现在您的项目拥有:

  • 🪐 包含业务逻辑的 Planet 模型
  • 📊 用于 PostgreSQL 中 planets 表的迁移
  • 🛠️ 配置好的模型属性(fillablecasts

准备好数据库! 在下一章中,我们将运行迁移并用第一批行星填充宇宙。

📌 检查:

确保 Planet.php..._create_planets_table.php 文件已在正确的目录中创建。

⚠️ 如果 Artisan 报错:

  • 检查您是否在项目文件夹中
  • 确保已安装依赖项(composer install
  • 对于 Windows:将 PHP 和 Composer 添加到 PATH