Laravel-Module 模組開發一:評論模組實現

可樂732發表於2019-05-06

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 協議》,轉載必須註明作者和本文連結

相關文章