php评论模块,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_type。commentable_id 用来保存文章或者视频的 ID 值,而 commentable_type 用来保存所属模型的类名。Eloquent 使用 commentable_type来决定我们访问关联模型时,要返回的父模型的「类型」。

然后执行 php artisan migrate

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

e2081bc9d47265375e6cb336992ed3b3.png

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 协议》,转载必须注明作者和本文链接

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值