Junior — Middle
Can you list the main types of relationships implemented in Eloquent ORM?
sobes.tech AI
Answer from AI
In Eloquent ORM (Laravel), the main types of relationships between models are:
-
One-to-One: each record is related to one record of another table.
public function userProfile() { return $this->hasOne(UserProfile::class); } -
One-to-Many: one record is related to many records of another table.
public function posts() { return $this->hasMany(Post::class); } -
Inverse One-to-Many: the inverse relationship to one.
public function user() { return $this->belongsTo(User::class); } -
Many-to-Many: records are related through an intermediate table.
public function roles() { return $this->belongsToMany(Role::class); } -
Polymorphic Relations: a relationship where a model can belong to multiple other models.
public function comments() { return $this->morphMany(Comment::class, 'commentable'); }
These relationship types allow for convenient working with relational data in Laravel.