Junior — Middle
Have you worked with foreign keys to ensure relationships between tables in a database?
sobes.tech AI
Answer from AI
Yes, foreign keys are used to ensure data integrity and relationships between tables in relational databases. In Node.js, when working with databases (such as PostgreSQL, MySQL), foreign keys are defined at the database schema level.
Example of creating tables with a foreign key in SQL:
CREATE TABLE users (
id SERIAL PRIMARY KEY,
name VARCHAR(100)
);
CREATE TABLE orders (
id SERIAL PRIMARY KEY,
user_id INTEGER REFERENCES users(id),
order_date DATE
);
In Node.js, you can use an ORM (such as Sequelize) to define such relationships programmatically:
const User = sequelize.define('User', { /* fields */ });
const Order = sequelize.define('Order', { /* fields */ });
Order.belongsTo(User, { foreignKey: 'user_id' });
User.hasMany(Order, { foreignKey: 'user_id' });
Thus, foreign keys help maintain relationships and integrity between tables.