前言
前面章节没看过的朋友请先从第一章开始看 。这章主要写文章相关功能。
后端
创建迁移文件命令
php artisan make:migration create_categories_table
编辑database/migrations/2025_07_11_210720_create_categories_table.php
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->id(); // 主键,自增ID
$table->string('name')->unique(); // 分类名称,唯一,如“技术”
$table->string('slug')->unique(); // 分类别名,URL 友好,如“tech”
$table->text('description')->nullable(); // 分类描述,可为空
$table->timestamps(); // 创建时间和更新时间
});
}
执行迁移
php artisan migrate
创建模型命令
php artisan make:model Category
编辑模型app/Models/Category.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
use HasFactory;
protected $fillable = ['name', 'slug', 'description'];
}
编辑种子文件database/seeders/DatabaseSeeder.php
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use App\Models\User;
use App\Models\Category;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* @return void
*/
public function run()
{
$this->call([
UserSeeder::class
]);
$admin = User::where('name', 'admin')->first();
// 创建分类
$categories = [
Category::create([
'name' => '技术分享',
'slug' => 'tech',
'description' => '分享最新技术、编程经验和开发技巧。',
]),
Category::create([
'name' => '生活随笔',
'slug' => 'life',
'description' => '记录生活点滴、感悟与随想。',
]),
Category::create([
'name' => '学习笔记',
'slug' => 'study',
'description' => '学习过程中的笔记、总结与心得。',
]),
];
}
}
这里我执行了
php artisan migrate:refresh --seed
不知道为啥不起作用。有懂的大佬说一下呗。
我这里直接删了数据库,重新运行迁移和种子文件了。以后加文章之类的应该还是这套操作。笨办法,嘻嘻。
php artisan migrate
php artisan db:seed
创建控制器命令
php artisan make:controller CategoryController
先吃个早饭。等会再来写了。嘻嘻