Featured image of post Day 16. Eloquent Relationships 一對多

Day 16. Eloquent Relationships 一對多

資源

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

前言

上一篇: Day 15. 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 多態的多對多

One To many (一對多)

文件
這裡因為我沒有想到,合適的架構所以就參考官方的表格關係,
我們假設一個貼文有多個留言,

表的關係

資料表關係如下

1
2
3
4
5
6
7
posts
    id - integer
    name - string
 
comments
    id - integer
    post_id integer

Model 設定

app/Models/Post.php

1
2
3
4
5
6
7
class Post extends Model
{
    public function comments()
    {
        return $this->hasMany(UserProfile::class);
    }
}

app/Models/Comment.php

1
2
3
4
5
6
7
class Comment extends Model
{
    public function post()
    {
        return $this->belongesTo(Post::class);
    }
}

這些 Model 關聯可以自定義欄位關聯,只是我都是使用預設的,
跟著 Laravel 的設計走,就輕鬆很多
不用額外指定欄位

舉例自定義

1
2
3
4
public function user()
{
    return $this->belongsTo(User::class, 'foreign_key', 'other_key');
}

如何使用

1
2
3
4
5
6
7
// 文章取得留言
$post = Post::find(1);
$comments = $post->comments;

// 留言取得文章
$comment = Comment::find(1);
$post = $comment->post;

小建議

我個人習慣 一對多的時候 function name會使用複數, 多對一的時候會使用單數
如此一來使用上就更符合語意

comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy