In this lesson, you will learn how to enforce a strict one-to-one relationship between two database tables by using unique constraints.
The Concept of One-to-One
A one-to-one relationship exists when a single record in Table A is associated with exactly one record in Table B. Think of a Users table and a Profiles table: every user has exactly one profile, and every profile belongs to exactly one user.
In a database, we implement this by placing a foreign key on one of the tables. However, to make it a true "one-to-one," we must ensure that the foreign key cannot be reused.
Enforcing Uniqueness
If we simply add a user_id column to the Profiles table, a user could theoretically have multiple profiles. To prevent this, we apply a Unique Constraint to that foreign key column. This tells the database: "Only one record may exist with this specific user_id."
Consider this schema definition logic:
// Migration for Profiles table
await db.schema.createTable('profiles', (table) => {
table.increments('id');
table.string('bio');
// The 'unique' method ensures no two profiles
// can share the same user_id
table.integer('user_id').unsigned().references('id').inTable('users').unique();
});
Why This Matters
By adding .unique() to the user_id column, you create a rigid structure at the persistence layer. Even if your Node.js application logic has a bug that tries to insert a second profile for the same user, the database engine will reject the operation with a constraint violation error. This is a critical safety net for data integrity; it ensures that your application state remains consistent without relying solely on application-level checks.
This mapping strategy is the foundation for splitting large entities into smaller, more manageable tables while maintaining a strictly logical 1:1 bond between them.
Key Takeaway: A one-to-one relationship is achieved by combining a foreign key reference with a unique constraint, ensuring that each foreign identifier can only appear once in the associated table.