Laravel-Module 模块开发一:评论模块实现

1、安装 Laravel 、生成用户表结构 make:auth

2、生成 文章视频评论

php artisan make:model Models/Article -m

php artisan make:model Models/Video -m

php artisan make:model Models/Comment -m

3、编辑迁移文件

database/migrations/2019_05_06_152532_create_articles_table.php

public function up()
    {
        Schema::create('articles', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->string('title');
            $table->text('body');
            $table->timestamps();
            $table->foreign('user_id')->references('id')->on('users');
        });
    }
database/migrations/2019_05_06_152610_create_videos_table.php

public function up()
    {
        Schema::create('videos', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->string('title');
            $table->string('url');
            $table->timestamps();
            $table->foreign('user_id')->references('id')->on('users');
        });
    }
database/migrations/2019_05_06_152635_create_comments_table.php

public function up()
    {
        Schema::create('comments', function (Blueprint $table) {
            $table->increments('id');
            $table->text('body');
            $table->integer('commentable_id');
            $table->string('commentable_type');
            $table->timestamps();
        });
    }

comments 表中有两个需要注意的重要字段 commentable_id 和 commentable_typecommentable_id 用来保存文章或者视频的 ID 值,而 commentable_type 用来保存所属模型的类名。Eloquent 使用 commentable_type来决定我们访问关联模型时,要返回的父模型的「类型」。

然后执行 php artisan migrate

现在我们的数据表应该是这样的

Laravel-Module 模块开发一:评论模块实现

4、接下来我们要写模型文件

App/Models/Article.php

class Article extends Model
{
    protected $fillable = ['title', 'body', 'user_id'];

    // 获得此文章的所有评论
    public function comments(){
        return $this->morphMany('Comment', 'commentable');
    }
}

App/Models/Video.php
同上

App/Models/Comment.php

class Comment extends Model
{
    // 获得拥有此评论的模型.
    public function commentable(){
        return $this->morphTo();
    }
}

模型填充自行解决

5、读取以及关联模型

//读取 ID 为 1 的文章下所有评论
$article = Article::find(1);
$comments = $article->comments();
//给 ID 为 1 的文章关联一条评论
$comment  =  new  App\Models\Comment(['body'  =>  'A new comment.']);  
$article  =  App\Models\Article::find(1);  
$article->comments()->save($comment);

//给 ID 为 1 的文章关联一条评论另一种方法
$article  =  App\Models\Article::find(1);  
$comment = $article->comments()->create(['body' => 'A new comment.']); 

save 方法和 create 方法的不同之处在于, save 方法接受一个完整的 Eloquent 模型实例,而 create 则接受普通的 PHP 数组

本作品采用《CC 协议》,转载必须注明作者和本文链接
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 1

那么如何实现回复评论呢?

5年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!