const Sequelize = require('sequelize');
const sequelize = require('../util/dbconnect');
const TableOne= sequelize.define('TableOne', {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true
},
awg: {
type: Sequelize.STRING,
allowNull: false
}
});
module.exports = TableOne;
**Table 2:**
const Sequelize = require('sequelize');
const sequelize = require('../util/dbconnect');
const Tabletwo= sequelize.define('Tabletwo', {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true
},
item_des: {
type: Sequelize.STRING,
},
gauge:{
type: Sequelize.STRING,
},
connector_type:{
type: Sequelize.STRING,
}
});
module.exports = Tabletwo;
how to create a foreign key for two existing tables and link them, it would be great if it could be explained as I had gone through the documentation but couldn't work it out.
You need to use belongsTo() notation for associating tables viz. foreign key.
TableOne.belongsTo(Tabletwo); // Will add TabletwoId to TableOne
OR
TableOne.belongsTo(Tabletwo, {as: 'Two'}); // Adds TwoId to TableOne rather than TabletwoId
You may refer https://sequelize.readthedocs.io/en/2.0/docs/associations/ for further details.
Related
i have define this model:
const Sequelize = require('sequelize');
const db = require("../database/db")
var Reparacion = db.sequelize.define('reparaciones', {
id: {
type: Sequelize.INTEGER,
allowNull: false,
autoIncrement: true,
primaryKey: true,
},
descripcion: {
type: Sequelize.STRING(255),
allowNull: true
},
fecha_inicio: {
type: Sequelize.DATEONLY,
allowNull: true
},
fecha_fin: {
type: Sequelize.DATEONLY,
allowNull: true
},
},{});
module.exports=Reparacion
In other model when I define the foreing Key in other model, the methods HasMany and belongsTo doesn't works because I call them on a function:
const Reparacion = require("./reparacion")
console.log(typeof(Vehiculo))
console.log(typeof(Reparacion))
Vehiculo.hasMany(Reparacion,{foreingKey:"vehiculoId", onDelete: 'cascade', sourceKey:"matricula"})
Reparacion.belongsTo(Vehiculo)
The both console log return: "function"
What i have to change for define correctly the association??
EDIT
that is de "Vehiculo" model:
const Sequelize = require('sequelize');
const db = require("../database/db")
var Vehiculo = db.sequelize.define('vehiculos', {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
primaryKey: true,
allowNull: true
},
matricula: {
type: Sequelize.STRING(45),
allowNull: false,
primaryKey: true,
},
marca: {
type: Sequelize.STRING(50),
allowNull: true
},
modelo: {
type: Sequelize.STRING(50),
allowNull: true
},
anio: {
type: Sequelize.INTEGER,
allowNull: true
},
color: {
type: Sequelize.STRING(20),
allowNull: true
},
puertas: {
type: Sequelize.INTEGER,
allowNull: true
},
motor: {
type: Sequelize.STRING(20),
allowNull: true
},
},{});
const Reparacion = require("./reparacion")
Vehiculo.hasMany(Reparacion,{foreingKey:"vehiculoMatricula", onDelete: 'cascade', sourceKey:"matricula"})
Reparacion.belongsTo(Vehiculo)
module.exports=Vehiculo
Well, it is expected that typeof Vehiculo and typeof Reparacion will return a function that happens because every constructor or class is a function in JS, so when you create a model for an entity it returns a function/constructor that can create an instance of an entity for you. So there is no problem with that.
And actually the documentation shows similar code https://sequelize.org/master/manual/assocs.html
This is the teacher Table's Schema
const { Sequelize, DataTypes } = require('sequelize');
const sequelize = require('../util/databaseConnection');
const Teacher = sequelize.define("teacher", {
teacherid: {
type: DataTypes.STRING,
allowNull: false,
primaryKey: true
},
surname: {
type: DataTypes.STRING,
allowNull: true
},
firstname: {
type: DataTypes.STRING,
allowNull: true
},
lastname: {
type: DataTypes.STRING,
allowNull: true
}
})
module.exports = Teacher;
This is the subject Model's Schema
const { Sequelize, DataTypes } = require("sequelize");
const sequelize = require('../util/databaseConnection');
const Subject = sequelize.define('subject', {
subjectid: {
type: DataTypes.INTEGER,
AutoIncrement: true,
primaryKey: true
},
subjectname: {
type: DataTypes.STRING
},
grade: {
type: DataTypes.STRING
},
subjectinfo: {
type: DataTypes.STRING
}
})
module.exports = Subject;
I need to define the association between teacher hasMany subject
Teacher.hasMany(Subject)
But following error
Naming collision between attribute 'subjects' and association
'subjects' on model teacher. To remedy this, change either foreignKey
or as in your association definition
You have to add Following keys
Teacher.hasMany(Subject, { foreignKey: 'teacher_id', targetKey: 'id' });
and in Subject model add following column
teacher_id: {
type: DataTypes.INTEGER,
allowNull: false,
references: {
model: 'teacher',
key: 'id'
}
},
I have a post route that is using the sequelize create method to add an event to the database. I have defined the tables for user and event as such:
Events
const Events = sequelize.define('Events', {
Event_id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true
},
name: {
type: DataTypes.STRING,
allowNull: false
},
month: {
type: DataTypes.STRING,
allowNull: false
},
day:{
type:DataTypes.INTEGER,
allowNull: false
},
year: {
type: DataTypes.INTEGER,
allowNull: false
},
important:{
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false
},
description:{
type: DataTypes.STRING,
allowNull: true
}
});
return Events;
}
User
const User = sequelize.define('Users', {
user_id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true
},
name: {
type: DataTypes.STRING,
allowNull: false
},
email: {
type: DataTypes.STRING,
allowNull: false
},
password: {
type: DataTypes.STRING,
allowNull: false
}
}, {});
User.associate = function(models){
User.hasMany(models.Events, {as: 'user'})
}
return User;
}
The post route seems to run correctly with the exception on sequelize not being able to attach the user Id to the event that is created do to
"Cannot add or update a child row: a foreign key constraint fails (planitdb.events, CONSTRAINT events_ibfk_1 FOREIGN KEY (UserUserId) REFERENCES users (user_id) ON DELETE SET NULL ON UPDATE CASCADE)"
I am not sure I understand exactly why this is happening. I am thinking I need to define the relation in the Events table as well? If that is the case, I am not sure I understand what type of relationship the Events table has with the User table. Or is the relationship a single event to a single user?
Any help would be greatly appreciated.
Your events object does not contain a mapping for user_id. This object needs to include a user_id field and this needs to be populated prior to attempting to insert a record to the events table.
EDIT - including sequelize relations solution:
Instead of this:
const Events = sequelize.define('Events', {...});
User.associate = function(models){
User.hasMany(models.Events, {as: 'user'})
}
Try:
const Events = sequelize.define('Events', {...});
const User = sequelize.define('User', {...});
User.hasMany(Events, {as: 'user'});
or:
const Events = sequelize.define('Events', {});
const User = sequelize.define('User', {...});
Events.belongsTo(User,{
foreignKey: 'user_id',
constraints: false,
as: 'user'
});
I am creating a cinema application. I have modeled the database on mySql but I am having trouble migrating it to Sequelize. I have followed the documentation but I am getting a lot of different errors.
I have tried using associations and indexes (as it should be). This is the model I am trying to make.
OCCUPIED_SEATS is composed of only two foreign keys and both make a unique index.
OCCUPIED_SEATS:
const SEATS = require("./Seats");
const SCREENING = require("./Screening");
const OCCUPIED_SEATS = sequelize.define("OCCUPIED_SEATS", {
//SEATS_ID
//SCREENING_ID
},
{
indexes: [
{
unique: true,
fields: [SEAT_ID, SCREENING_ID]
}
],
underscored: true
}
);
module.exports = OCCUPIED_SEATS;
SEATS:
const OCCUPIED_SEATS = require("./Occupied_Seats");
const SEATS = sequelize.define("SEATS", {
SEATS_ID: {
type: Sequelize.INTEGER,
primaryKey: true,
allowNull: false,
autoIncrement: true
},
ROW: {
type: Sequelize.STRING,
allowNull: false,
},
COLUMN: {
type: Sequelize.INTEGER,
allowNull: false
},
},
{
underscored: true
}
);
SEATS.hasMany(OCCUPIED_SEATS, {foreignKey: 'SEAT_ID'})
module.exports = SEATS;
SCREENING:
const OCCUPIED_SEATS = require("./Occupied_Seats");
const SCREENING = sequelize.define("SCREENING", {
SCREENING_ID: {
type: Sequelize.INTEGER,
primaryKey: true,
allowNull: false,
autoIncrement: true
},
SCREENING_START_TIME: {
type: Sequelize.TIME,
allowNull: false,
},
DATE: {
type: Sequelize.DATE,
allowNull: false
}
},
{
underscored: true,
indexes: [
{
unique: true,
fields: [ROOM_ID, SCREENING_START_TIME, DATE]
}
]
}
);
SCREENING.hasMany(OCCUPIED_SEATS, {foreignKey: 'SCREENING_ID'});
module.exports = SCREENING;
The error I am getting when I try this is:
[💻] Error: SEATS.hasMany called with something that's not a subclass of Sequelize.Model
How should I code the model?
Looks like in the new version of Sequelize you have to define your models through Sequelize.Model type:
class Seats extends Sequelize.Model {}
Seats.init({
id: {
type: Sequelize.INTEGER,
primaryKey: true,
allowNull: false,
autoIncrement: true
},
row: {
type: Sequelize.STRING,
allowNull: false,
},
...
});
module.exports = Seats;
And then somewhere else:
Seats.hasMany(OccupiedSeatc, {foreignKey: 'SEAT_ID'})
See model definition docs and accociation docs.
"I have 2 tables "Users" and "Profile_personals". How do I add a foreign key constraint to my profile personals using my "user_id" primary that's inside my Users table? I'm working with node.js, sequelize mysql.
Users(parent Table):
const Sequelize = require('sequelize')
const db = require("../database/db.js")
module.exports = db.sequelize.define(
"users",
{
user_id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
email: {
type: Sequelize.STRING
},
password: {
type: Sequelize.STRING
}
},
{
timestamps: false
}
)
Personals(Child Table):
const Sequelize = require('sequelize')
const db = require("../database/db.js")
module.exports = db.sequelize.define(
'profile_personals',
{
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
biography: {
type: Sequelize.STRING
}
},
{
timestamps: false
}
)
Do it this way, I hope it's what you're looking for.
module.exports = db.sequelize.define(
'profile_personals',
{
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
biography: {
type: Sequelize.STRING
},
// It is possible to create foreign keys:
user_id: {
type: Sequelize.INTEGER,
references: {
// This is a reference to another model
model: Users,
// This is the column name of the referenced model
key: 'user_id'
}
}
},
{
timestamps: false
}
);