In this article, we explore how to establish relationships within a relational database to connect different tables—in our case, a “users” table and a “posts” table. In many applications, such as social media platforms, a post is always associated with its creator. However, our current setup lacks this connection: users and posts are managed independently without any inherent link between a post and the user account that created it. When examining the posts table, you’ll notice columns such as ID, title, content, published status, and a created_at timestamp (not shown here). Yet, there is no column that indicates which user created a particular post.Documentation Index
Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
Use this file to discover all available pages before exploring further.
Establishing Relationships with Foreign Keys
Relational databases excel at forming connections between tables. To associate each post with a specific user, we need to add a new column—commonly called “user_id”—to the posts table. This column will serve as a foreign key that references the ID column in the users table. Below is an example SQL statement illustrating how to alter the posts table to add this relationship:While the primary key (ID) is typically used as the foreign key target, some advanced database designs might involve referencing columns other than the primary key, tailored to specific business logic and relationship requirements.
Visualizing the Relationship
The diagram below illustrates the one-to-many relationship between the “users” and “posts” tables. In this relationship, one user can create many posts, but each post is linked to only one user.