菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
1235
0

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

原创
05/13 14:22
阅读数 2762

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 数组

发表评论

0/200
1235 点赞
0 评论
收藏
为你推荐 换一批