Featured image of post Day 20. Eloquent Polymorphic Relationships 多態的多對多

Day 20. Eloquent Polymorphic Relationships 多態的多對多

資源

Laravel7 30天: 目錄
專案連結: github - laravel7 之 30 天分享

前言

上一篇: Day 19. Eloquent Polymorphic Relationships 多態的一對多

今天要來分享 多態的多對多

關聯表文章區

關聯名稱傳送門
One To One一對一Day 15. Eloquent Relationships 一對一
One To Many多對多Day 16. Eloquent Relationships 一對多
Many To Many多對多Day 17. Eloquent Relationships 多對多
Polymorphic One To One多態的一對一Day 18. Eloquent Polymorphic Relationships 多態的一對一
Polymorphic One To Many多態的一對多Day 19. Eloquent Polymorphic Relationships 多態的一對多
Polymorphic Many To Many多態的多對多Day 20. Eloquent Polymorphic Relationships 多態的多對多

主要內容

文件

表的關係

假設我們今天要設計標籤管理
貼文有標籤
影片也有標籤
甚至標籤也有自己的資訊
就是可以透過 第3張表多對多的方式關聯他們

資料表關係如下

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
posts
    id - integer
    name - string
 
videos
    id - integer
    name - string
 
tags
    id - integer
    name - string
 
taggables
    tag_id - integer
    taggable_id - integer
    taggable_type - string

Model 設定

app/Models/Tag.php

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Tag extends Model
{
    // 關聯貼文
    public function posts()
    {
        return $this->morphedByMany(Post::class, 'taggable');
    }
 
    // 關聯影片
    public function videos()
    {
        return $this->morphedByMany(Video::class, 'taggable');
    }
}

app/Models/Post.php

1
2
3
4
5
6
7
class Post extends Model
{
    public function tags()
    {
        return $this->morphToMany(Tag::class, 'taggable');
    }
}

app/Models/Video.php

1
2
3
4
5
6
7
class Video extends Model
{
    public function tags()
    {
        return $this->morphToMany(Tag::class, 'taggable');
    }
}

如何使用

  • 取得
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14

$post = Post::find(1);
// post 取得 tag 
foreach ($post->tags as $tag) {
    //
}


$tag = Tag::find(1);
 
#  tag 取得 video
foreach ($tag->videos as $video) {
    //
}
comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy