Relationships định nghĩa mối liên kết giữa các model. One-to-Many: User có nhiều Post. Định nghĩa trong User model: public function posts() { return $this->hasMany(Post::class); }. Truy cập: $user->posts. Many-to-One (nghịch đảo): Post belongs to User. One-to-One: User có một Profile. Many-to-Many: Post có nhiều Tag.
Ví dụ: $post->tags()->attach($tagId) tạo liên kết. Polymorphic: nhiều model cùng liên kết đến một model (như Comment trên cả Post và Video). Relationships cho phép query dữ liệu trực quan: $user->posts()->where("published", true)->get() thay vì SQL join phức tạp.
Relationships define connections between models. One-to-Many: User has many Posts. Define in User model: public function posts() { return $this->hasMany(Post::class); }. Then access: $user->posts. Many-to-One (inverse): Post belongs to User. One-to-One: User has one Profile. Many-to-Many: Posts have many Tags.
Example: $post->tags()->attach($tagId) associates. Polymorphic: multiple models relate to one (like Comments on Posts and Videos). Relationships enable intuitive data querying: $user->posts()->where("published", true)->get() vs complex SQL joins.