DB seeds with relations

In relational database­s, tables are often linked to each other using foreign ke­ys. The type of relationship be­tween these­ tables depends on the number of entities involve­d.

  • One-to-one­ relationship: In a one-to-one re­lationship, two tables are connected in such a way that each record in one table­ is associated with only one record in the other table. For instance, each user can only have one profile­.

  • One-to-many: These re­lationships occur when a record in one table­ is associated with multiple records in another table. For instance, a user can have multiple posts.

  • Many to many: A many-to-many relationship is a relationship between two tables where one record in one table can be related to many forms in the other table and vice versa. For instance, a user can have numerous tags, and several users can have labels associated with them.

  • Polymorphic: A polymorphic relationship is a relationship between two tables where the relationship can be of different types. For example, a comment can relate to a user or a post.

In order to implement relations among tables, some modifications need to be implemented between the table models. To understand the users and posts table example, we need to make the following modifications:

Step 1: Create the migrations table

First, we need to execute the following migrations to create the posts and users tables:

Get hands-on with 1400+ tech skills courses.