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
现在我们的数据表应该是这样的
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 协议》,转载必须注明作者和本文链接
推荐文章: