Junior — Middle
Can you list the existing types of relationships between models in Laravel?
sobes.tech AI
Answer from AI
In Laravel, the following are the main types of relationships between models:
- One to One — one record in a table is related to one record in another.
- One to Many — one record is related to many records in another table.
- Many to Many — many records are related to many records in another table through a pivot table.
- Polymorphic Relations — allow a model to belong to more than one other model on a single association.
Example of a "One to Many" relationship:
class Post extends Model {
public function comments() {
return $this->hasMany(Comment::class);
}
}
class Comment extends Model {
public function post() {
return $this->belongsTo(Post::class);
}
}
These relationships make it convenient to work with data and build complex queries using Eloquent ORM.