4. Defining Relationships Between Posts and Users

After creating the posts table migration, I then defined the relationship that a post has with a user, which is that many posts can belong to one user - this is achieved with the belongsTo() method. To make the relationship function more semantic, I've named it author - as writers of posts would be considered as authors. For this reason, I also had to specify the foreign key, instead of letting Laravel assume that it was author_id - which doesn't exist. Below is a screen capture of the relationship in the post model (App/Models/Post.php). 


The flip-side of this is on the user side, where I need to state the inverse relationship. In this case, one user can have many posts - this is defined with the hasMany() method. Below is a screen capture of the relationship from the user model (App/Models/User.php).



Comments