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'
});
Related
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.
I have two services: posts and comments. Every post can have multiple comments. User 1 creates a post, user 2 creates a comment inside this post. Both users should be able to update, patch or delete the created comment. How do I correctly qualify both users to modify the comment created by user 2?
Posts model
{
userId: { type: DataTypes.INTEGER, allowNull: false },
text: { type: DataTypes.TEXT, allowNull: false },
};
posts.associate = function (models) {
posts.hasMany(models.comments, { onDelete: 'CASCADE' });
}
Comments model
{
userId: { type: DataTypes.INTEGER, allowNull: false },
postId: { type: DataTypes.INTEGER, allowNull: false },
text: { type: DataTypes.TEXT, allowNull: false },
};
comments.associate = function (models) {
comments.belongsTo(models.posts);
}
Posts can only be deleted by the post-creator, so setField from the feathers-authentication-hooks does a good job in this case. But how do I qualify the post-creator to manage comments inside his post?
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
}
);
So, assume we have that Sequelize model:
var User = sequelize.define("User", {
id: {
type: DataTypes.STRING(45),
allowNull: false,
primaryKey: true
},
password: {
type: DataTypes.STRING(60),
allowNull: false
},
email: {
type: DataTypes.STRING(45),
allowNull: false,
unique: true
},
firstName: {
type: DataTypes.STRING(45),
allowNull: true,
defaultValue: null
}
},
{
tableName: 'profiles',
classMethods: {
associate: function(models) {
User.belongsToMany(User, {through: 'friends', as:'friend'});
}
}
});
after calling associate() method, it will create an extra table friends with columns userId, friendId, createdAt and updatedAt. The case is I need to use this table with safe-deleting mode, in other words, I have to add 'deleted' column somehow. I tried to use paranoid: true in belongsToMany's attributes, didn't work. Is there any ways to do it?
Maybe you can create an model/table which name is Friend. And you can set paranoid: true in that model. And when you deleted an User, it keeps User's friend relation was keeping in that model.
I hope it works. :)