什麼是 morph

假如你有一篇部落格,裡面有 Post 跟 News,前者放你的文章,後者放最新消息。

這兩者都需要留言 Comment 的功能,因此資料結構上, Comment 同時 belongs to Post 跟 News

在 Laravel 當中,有快速搭建這種多元關聯的功能,那就是 morphs

何時使用 morph

多個資料表需同時關聯某一資料表時,就可使用 morph,達到快速搭建、統一規格、簡單明瞭的多元關聯。

更多使用 morph 的例子

如何使用 morph

migration

class CreateCommentsTable extends Migration
{
	public function up()
	{
		Schema::create('comments', function (Blueprint $table) {
			$table->id();
			$table->text('content');
			$table->BigUnsignedInteger('author_id');
			**$table->morphs('commentable');**
			$table->timestamps();
		});
	}
	
	public function down()
	{
		Schema::dropIfExists('comments');
	}
}

model

class Comment extends Model
{
	public function commentable() {
	  return $this->morphTo();
	}
}

class Post extends Model
{
	public function comments()
	{
		return $this->morphToMany(Comment::class, 'commentable')
	}
}

class News extends Model
{
	public function comments()
	{
		return $this->morphToMany(Comment::class, 'commentable')
	}
}

善用 Trait,更方便管理