从零构建 Laravel 论坛二:搭建舞台
一、 新建项目
创建项目
composer create-project laravel/laravel forum --prefer-dist "8.6.6"
引入 Laravel Breeze 用户认证包
composer require laravel/breeze php artisan breeze:install npm install npm run dev php artisan migrate
二、 创建基础表
本项目中,最基础的模型为 Topic (话题)、 Comment (评论) 、 User (用户)
User 表 Laravel 自带先不做修改
2.1、 新建 Topic
创建 Topic 相关文件
php artisan make:model Topic -a
-a 将会自动生成对应的 Model、Factory、Migration、Seeder、Controller、Policy 等文件
修改 Migration 文件
. . public function up() { Schema::create('topics', function (Blueprint $table) { $table->id(); $table->integer('user_id'); $table->string('title'); $table->longText('body'); $table->timestamps(); }); } . .
运行迁移
php artisan migrate
修改 Model 文件
. . protected $fillable = ['user_id', 'title', 'body']; public function user() { return $this->belongsTo(User::class); } . .
修改 Factory 文件
. . use App\Models\User; . . public function definition() { return [ 'user_id' => User::factory(), 'title' => $this->faker->sentence, 'body' => $this->faker->paragraph, ]; } . .
修改 Seeder 文件
. . use App\Models\User; use App\Models\Topic; . . public function run() { $users = User::all(); foreach ($users as $user) { Topic::factory() ->count(mt_rand(0, 10)) ->create([ 'user_id' => $user->id ]); } } . .
2.2、 新建 Comment
创建 Comment 相关文件
php artisan make:model Comment -a
修改 Migration 文件
. . public function up() { Schema::create('comments', function (Blueprint $table) { $table->id(); $table->integer('topic_id'); $table->integer('user_id'); $table->text('body'); $table->timestamps(); }); } . .
运行迁移
php artisan migrate
修改 Model 文件
. . protected $fillable = ['user_id', 'topic_id', 'body']; public function user() { return $this->belongsTo(User::class); } public function topic() { return $this->belongsTo(Topic::class); } . .
修改 Factory 文件
. . use App\Models\User; use App\Models\Topic; . . public function definition() { return [ 'topic_id' => Topic::factory(), 'user_id' => User::factory(), 'body' => $this->faker->paragraph, ]; } . .
修改 Seeder 文件
. . use App\Models\User; use App\Models\Topic; use App\Models\Comment; . . public function run() { $topics = Topic::all(); foreach ($topics as $topic) { $users = User::inRandomOrder()->limit(mt_rand(0, 3))->get(); foreach ($users as $user) { Comment::factory() ->count(mt_rand(0, 3)) ->create([ 'user_id' => $user->id, 'topic_id' => $topic->id, ]); } } } . .
2.3、 填充测试数据
修改 DatabaseSeeder 文件
public function run() { User::factory(10)->create(); $this->call([ TopicSeeder::class, CommentSeeder::class, ]); }
运行填充
php artisan db:seed
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: