In a one-to-one relationship, one record in a table is associated with exactly one record in another table. For example, a User
has one Profile
.
Steps:
Define the relationship in the User
model:
class User extends Model
{
public function profile()
{
return $this->hasOne(Profile::class);
}
}
Profile
model:class Profile extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
In a one-to-many relationship, one record in a table is associated with multiple records in another table. For example, a Post
can have many Comments
.
Steps:
Define the relationship in the Post
model:
class Post extends Model
{
public function comments()
{
return $this->hasMany(Comment::class);
}
}
Comment
model:class Comment extends Model
{
public function post()
{
return $this->belongsTo(Post::class);
}
}
In a many-to-many relationship, multiple records in one table are associated with multiple records in another table. For example, a User
can have many Roles
, and a Role
can belong to many Users
.
Steps:
Define the relationship in the User
model:
class User extends Model
{
public function roles()
{
return $this->belongsToMany(Role::class);
}
}
Profile
model:class Role extends Model
{
public function users()
{
return $this->belongsToMany(User::class);
}
}
A "Has Many Through" relationship allows you to define a relationship through an intermediate model. For example, a Country
has many Post
records through User
.
Steps:
Country
model:class Country extends Model
{
public function posts()
{
return $this->hasManyThrough(Post::class, User::class);
}
}
Example Usage:
$country = Country::find(1);
$posts = $country->posts; // Get all posts associated with the country through users
Eloquent relationships make it easy to work with complex data models by defining associations between them. Whether it's one-to-one, one-to-many, many-to-many, or polymorphic relationships, Laravel provides a straightforward approach to manage and query data relationships, streamlining database interactions and improving code readability.