Laravel Eloquent Relationships
Laravel-er Eloquent relationships hocche model-gulor moddhe relation establish korar ekta powerful system. Ekhane ami One to One theke shuru kore Polymorphic porjonto shob gulo relationship Banglay explain korbo, example code shoho. Simple & complex duita rokomer example-i dibo.
1. One to One Relationship (একজন user এর একটি profile)
Simple Example:
User Model:
Profile Model:
Use Example:
2. One to Many Relationship (একটা post-এর একাধিক comment)
Simple Example:
Post Model:
Comment Model:
Use Example:
3. Many to Many Relationship (একজন student একাধিক course-e porche, r ekta course-e onek student ache)
Simple Example:
Student Model:
Course Model:
Pivot Table: course_student with student_id, course_id
Use Example:
4. Has Many Through (ekta country-r onek user ache, user-r onek post ache — country diye post ber kora)
Complex Example:
Country Model:
Use Example:
5. Polymorphic Relationship (ekoi table er record onek model theke ashte pare, e.g. comments for posts, videos)
Simple Polymorphic (comment on post or video)
Migration:
Comment Model:
Post Model:
Video Model:
Use Example:
6. Polymorphic Many to Many (Tagging system: Post & Video both can have Tags)
Complex Polymorphic Example:
Tables:
-
tags -
taggables(tag_id, taggable_id, taggable_type)
Tag Model:
Post & Video Models:
Use Example:
Bonus: Load Relationships with Eager Loading
Summary Table (Banglay)
| Relationship Type | Description (Banglay) |
|---|---|
| One to One | ১টা user এর ১টা profile |
| One to Many | ১টা post এর অনেক comment |
| Many to Many | ১টা student onek course e, ১ta course onek student e |
| Has Many Through | Country → Users → Posts |
| Polymorphic One to Many | Post o Video er upor comment |
| Polymorphic Many to Many | Post o Video er upor tag |
No comments