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

Day 18. Eloquent Polymorphic Relationships 多態的一對一

資源

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

前言

上一篇: Day 17. Eloquent 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
users
    id - integer
    name - string
 
posts
    id - integer
    name - string

images
    id - integer
    url - string
    imageable_id - integer
    imageable_type - string

Model 設定

app/Models/Image.php

1
2
3
4
5
6
7
class Image extends Model
{
    public function imageable()
    {
        return $this->morphTo();
    }
}

app/Models/User.php

1
2
3
4
5
6
7
class User extends Model
{
    public function image()
    {
        return $this->morphOne(Image::class, 'imageable');
    }
}

app/Models/Post.php

1
2
3
4
5
6
7
class Post extends Model
{
    public function image()
    {
        return $this->morphOne(Image::class, 'imageable');
    }
}

如何使用

  • 取得
1
2
3
4
5
6
// 會員取得圖片
$user = User::find(1);
$image = $user->image;

$image = Image::find(1);
$imageable = $image->imageable;
comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy