The Beginner Guide To Laravel ORM:Legacy Perspective (Part 2)
Previously I published an article on one-to-one relationship. Today i will continue on one-to-many relationship and show how it be done in laravel ORM. Let’s look at the picture below.
In the picture above, we see that user has many posts and a post has many comments. So how do we put this in code? Let’s take a look at the code.
For the purpose of this example, I created 3 models that are User, Post and Comment. The table design was intentionally created to support the context of the legacy convention. The user table is called legacy because its primary key (id) being named against the default naming convention of Laravel like post_id instead of using id as primary key.
The relation is obvious for these 3 models. Let me simplify,
1. User has many posts
- One User(User Model) Has Many (Relationship) post (Post Model)
- User key: passport_number, post key: post_id
2. Post has many comments
- One Post(Post Model) Has Many (Relationship) comments (Comment
Model)
- Post key: post_id, comment key: comment_id
If we scroll through the codes below, you can that see that User model contains,
public function posts(){
return $this->hasMany('App\Post','local_key(passport_number_in_user_model)','other_key(passport_number_in_post_model)');
}
In Laravel ORM for one-to-many relationship, it uses the same pattern for both side of the table which is in this context, User -> Post or Post -> User
. Same goes to Post -> Comment or Comment -> Post.
This is how we create the relationship in Laravel ORM.
The User
model can be translated to as a user has many posts
In the Post
model, we can see that one or more posts are belongs to a user
. and if we look again at the user()
method, we can see the same pattern which I already explained in User
model.
In the Comment
model, which tells us one or more comments are belongs to a post
The expected results from the above example are.
1. Get the first post and get the comments for the post.
(You can use where condition to get the post before the comments)
2. Get the first comment and show the post which comment is belongs to.
3. Get the first post and get the user who wrote the post.
4. Get the user by passport_number, and get the user posts
As we can see, we now know that we can implement many-to-many relationship using Laravel ORM for the legacy database as well.
In the next tutorial I will show you how to handle Many To Many relationship on legacy perspective.
To be continued in part 3…
Thanks for reading.