Laravel Eloquent provides an easy-to-use and expressive way to define relationships between database tables. There are several types of relationships that can be defined in Eloquent, including:
1. One-to-One Relationship:
In a one-to-one relationship, a record in the parent table (e.g. users) can be associated with only one record in the child table (e.g. profiles), and vice versa. Here's an example:
// 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 this example, the User
model has a hasOne
relationship with the Profile
model, and the Profile
model has a belongsTo
relationship with the User
model. To retrieve the profile of a user, you can use:
$user = User::find(1); $profile = $user->profile;
2. One-to-Many Relationship:
In a one-to-many relationship, a record in the parent table (e.g. posts) can be associated with multiple records in the child table (e.g. comments), but a record in the child table can be associated with only one record in the parent table. Here's an example:
// 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 this example, the Post
model has a hasMany
relationship with the Comment
model, and the Comment
model has a belongsTo
relationship with the Post
model. To retrieve all comments of a post, you can use:
$post = Post::find(1); $comments = $post->comments;
3. Many-to-Many Relationship:
In a many-to-many relationship, a record in one table (e.g. users) can be associated with multiple records in another table (e.g. roles), and vice versa. Here's an example:
// User Model class User extends Model { public function roles() { return $this->belongsToMany(Role::class); } } // Role Model class Role extends Model { public function users() { return $this->belongsToMany(User::class); } }
In this example, the User
model has a belongsToMany
relationship with the Role
model, and the Role
model has a belongsToMany
relationship with the User
model. To retrieve all roles of a user, you can use:
$user = User::find(1); $roles = $user->roles;
That's it! We've successfully completed basic relationships, for advance level we will meet soon.
Top comments (0)