假如你有一篇部落格,裡面有 Post 跟 News,前者放你的文章,後者放最新消息。
這兩者都需要留言 Comment 的功能,因此資料結構上, Comment 同時 belongs to Post 跟 News
在 Laravel 當中,有快速搭建這種多元關聯的功能,那就是 morphs
。
當多個資料表需同時關聯某一資料表時,就可使用 morph,達到快速搭建、統一規格、簡單明瞭的多元關聯。
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');
}
}
commentable_id
, commentable_type
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
,更方便管理