How do Eloquent relationships like hasMany, belongsTo, and belongsToMany let you define and query connections between different database tables?
Short answer
Eloquent relationships are defined as methods on a model that describe how it relates to another model, such as hasMany for a one to many relationship like a user having many orders, belongsTo for the inverse side of that same relationship, and belongsToMany for a many to many…
Advertisement
AModel answer
Eloquent relationships are defined as methods on a model that describe how it relates to another model, such as hasMany for a one to many relationship like a user having many orders, belongsTo for the inverse side of that same relationship, and belongsToMany for a many to many relationship like students enrolled in multiple courses, and once defined, these relationships let you query related data using simple, readable method calls rather than writing manual join queries yourself.
class User extends Model {
public function orders() {
return $this->hasMany(Order::class);
}
}
$user = User::find(1);
$orders = $user->orders;Real-world example
An e commerce application defines a hasMany relationship between User and Order models, letting the application retrieve all of a specific customer's orders with a simple, readable property access rather than writing a manual SQL join query.
Likely follow-ups
- What is the difference between accessing a relationship as a property versus calling it as a method?
- What is the N plus one query problem and how do Eloquent relationships relate to it?
Related topics