[[:oktatas:web:back-end_framework:express|< Express]] ====== Express - Összekötés ====== * **Szerző:** Sallai András * Copyright (c) 2024, Sallai András * Licenc: [[https://creativecommons.org/licenses/by-sa/4.0/|CC Attribution-Share Alike 4.0 International]] * Web: https://szit.hu ===== Idegenkulcs megadása ===== A modellben: Employee.belongsTo(Position, {foreignKey: 'positionId', targetKey: 'id'}) Az Employee modell teljes kódja: const { DataTypes } = require('sequelize') const sequelize = require('../database/database') const Position = require('../models/position') const Employee = sequelize.define('Employee', { id: { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true }, name: { type: DataTypes.STRING, allowNull: false, validate: { notNull: true } }, city: { type: DataTypes.STRING, allowNull: true }, salary: { type: DataTypes.DOUBLE , defaultValue: 0 }, positionId: { type: DataTypes.INTEGER } }) //Idegenkulcs: Employee.belongsTo(Position, {foreignKey: 'positionId', targetKey: 'id'}) //A model és az adatbázis szinkronizálása, nem erőltetve. sequelize.sync({ force: false }) module.exports = Employee ===== Lekérdezés ===== A kontrollerben egy lehetséges lekrédezés: const emps = await Employee.findAll({ include: [{ model: Position }] }) ===== Lehetséges kimenet ===== { "data": [ { "Position": { "createdAt": null, "id": 1, "name": "fejlesztő", "updatedAt": null }, "city": "Hatvan", "createdAt": "2024-03-10T18:15:02.000Z", "id": 7, "name": "Csoda Béla", "positionId": 1, "salary": 394, "updatedAt": "2024-03-10T18:15:02.735Z" }, { "Position": { "createdAt": null, "id": 1, "name": "fejlesztő", "updatedAt": null }, "city": "Szolnok", "createdAt": "2024-03-10T18:15:28.000Z", "id": 8, "name": "Csík Ferenc", "positionId": 1, "salary": 392, "updatedAt": "2024-03-10T18:15:28.361Z" }, { "Position": { "createdAt": null, "id": 2, "name": "tesztelő", "updatedAt": null }, "city": "Szeged", "createdAt": "2024-03-10T18:15:54.000Z", "id": 9, "name": "Erős István", "positionId": 2, "salary": 397, "updatedAt": "2024-03-10T18:15:54.954Z" } ], "success": true }