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 协议》,转载必须注明作者和本文链接
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
讨论数量: 1

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

4年前 评论

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