I have created the following model in sequelize:
export function initialize(sequelize: Sequelize.Sequelize, dataTypes: Sequelize.DataTypes): SalesPerson.Model {
var salesPersonModel = sequelize.define<SalesPerson, SalesPerson.Pojo>('salesPerson', {
ownerId: { type: dataTypes.STRING, allowNull: false, field: 'owner_id' },
firstName: { type: dataTypes.STRING, allowNull: false, field: 'first_name' },
lastName: { type: dataTypes.STRING, allowNull: false, field: 'last_name' },
email: { type: dataTypes.STRING, allowNull: false }
}, {
underscored: true,
tableName: 'sales_persons'
});
salesPersonModel.removeAttribute('id');
return salesPersonModel;
}
after starting sequelize.sync() the table is correctly created. the problem is that when I make a query like this:
db.SalesPerson.find({ limit: 1, order: [['updated_at DESC']] })...
I got the following error:
Unhandled rejection SequelizeDatabaseError: ER_BAD_FIELD_ERROR: Unknown column 'salesPerson.updated_at DESC' in 'order clause'
and this has not sense because I see in the database the column so should be something related with sequelize
That's not how the syntax works. You need to separate the column name from the direction:
db.SalesPerson.find({ limit: 1, order: [['updated_at', 'DESC']] })...
Related
These are my models
Files
exports.models = File = sequelize.define("File", {
originalname: {
type: DataTypes.STRING,
allowNull: false,
},
destination: {
type: DataTypes.STRING,
allowNull: false,
},
filename: {
type: DataTypes.STRING,
allowNull: false,
},
path: {
type: DataTypes.STRING,
allowNull: false,
},
});
Sales
exports.models = Sales = sequelize.define("sales", {
OrderDate: {
type: DataTypes.STRING,
allowNull: false,
},
Region: {
type: DataTypes.STRING,
allowNull: false,
},
City: {
type: DataTypes.STRING,
allowNull: false,
},
Category: {
type: DataTypes.STRING,
allowNull: false,
},
Product: {
type: DataTypes.STRING,
allowNull: false,
},
Quantity: {
type: DataTypes.STRING,
allowNull: false,
},
UnitPrice: {
type: DataTypes.STRING,
allowNull: false,
},
TotalPrice: {
type: DataTypes.STRING,
allowNull: false,
},
});
and now I add the relation
await File.hasMany(Sales);
await Sales.belongsTo(File);
await sequelize
.sync({ force: true })
.then(async () => {
console.log("Database & tables created!");
})
.catch((err) => {
console.log("Error: " + err);
});
});
now with the sync method
the ORM Creates my Tables with all the columns that I have defined and additionally, it will create an id column in both the Sales and Files Tables automatically along with a FileID column in the Sales table as a foreign key
And Now
try {
await File.create(req.file);
} catch (err) {
console.log(err);
res
.status(500)
.json({ message: "Server Error File NOt Uploaded To Database" });
return;
}
try {
await Sales.bulkCreate(data);
} catch (error) {
console.log(error);
res
.status(500)
.json({ message: "Internal Server Error Data canot be uploaded" });
return;
}
when I try to insert data into my Database all the data is inserted correctly except for the foreign key which is null
I tried putting the NOT Null Constrain in there but after I do that the database returns an error which basically says that this table can not have this constrain
to my knowledge I have tried everything under sun and I really need help
Thank you in advance
I had this code block working with Sequelize v5. But since switching to v6, it seems to be erroring out. I am getting the error: Error: Invalid value { customer_id: 'dg5j5435r4gfd' }.
And here is the code that creates the where condition block:
let whereBlock = {
deleted_at: null,
};
if (args.includeCore) {
if (customerID !== 'all') {
// whereBlock[Op.or] = [
// { customer_id: customerID },
// { customer_id: coreCustomerID },
// ];
whereBlock[Op.or] = [];
whereBlock[Op.or].push({
customer_id: customerID,
});
whereBlock[Op.or].push({ customer_id: coreCustomerID });
}
} else {
whereBlock.customer_id = customerID;
}
I was using the commented code. And then I tried the code below that. Both are producing the same error. But when I remove all that code from the if block and just put in whereBlock.customer_id = customerID;, then it works fine. So I know the issue is how I am constructing the where condition.
Update: As requested, here is my Sheets model where the where clause is being run on.
'use strict';
export default (sequelize, DataTypes) => {
return sequelize.define(
'Sheet',
{
id: {
type: DataTypes.UUID,
primaryKey: true,
defaultValue: DataTypes.UUIDV4,
},
sheet_name: {
type: DataTypes.STRING,
isAlphaNumeric: true,
required: true,
allowNull: true,
len: [3, 80],
},
sheet_file_name: {
type: DataTypes.STRING,
unique: true,
isAlphaNumeric: true,
required: false,
allowNull: true,
},
brand_name: {
type: DataTypes.STRING,
unique: false,
isAlphaNumeric: true,
required: false,
allowNull: true,
},
customer_id: {
// fk in customers table
type: DataTypes.TINYINT(2).UNSIGNED,
required: true,
allowNull: false,
},
chemical_id: {
// fk in loads table
type: DataTypes.SMALLINT.UNSIGNED,
required: true,
allowNull: false,
},
load_id: {
// fk in loads table
type: DataTypes.SMALLINT.UNSIGNED,
required: true,
allowNull: false,
},
active: {
type: DataTypes.BOOLEAN,
required: true,
allowNull: false,
defaultValue: true,
},
created_at: {
type: DataTypes.DATE,
},
updated_at: {
type: DataTypes.DATE,
},
deleted_at: {
type: DataTypes.DATE,
},
},
{
underscored: true,
paranoid: false,
}
);
};
And in my index I have this to associate sheets with customers: db.Sheet.belongsTo(db.Customer);
Also here is the full code where the whereBlock is used, if that helps:
const files = await db.Sheet.findAll({
raw: true,
attributes: [
'sheet_name',
'sheet_file_name',
['brand_name', 'brand'],
'updated_at',
'active',
[Sequelize.col('Chemical.name'), 'chemical'],
[Sequelize.col('Load.value'), 'load'],
],
include: [
{
model: db.Load.scope(null),
required: true,
as: 'Load',
attributes: ['value'],
},
{
model: db.Chemical.scope(null),
required: true,
as: 'Chemical',
attributes: ['name'],
},
],
// model: model,
where: whereBlock,
order: [['active', 'DESC']],
});
TLDR: So here is what it comes down to:
whereBlock = {
deleted_at: null,
customer_id: customerID,
// [Op.or]: [
// { customer_id: customerID },
// { customer_id: coreCustomerID },
// ],
};
That code above works, but the commented code errors out with: Error: Invalid value { customer_id: '123456' }
OK, this is very weird. But I finally figured out the issue!! Was not something I would have thought of, just found it by chance. It was the way I was importing Op from sequelize.
import Op from 'sequelize';
So apparently, that Op object has another object inside it called Op. So when I call my [Op.or], I instead need to do this: [Op.Op.or].
I did try switching my import to import Op.Op from 'sequelize'; and that caused errors. Anyone know how I can properly import the inner object?
Update
OK, so apparently in my other DB files, I was doing the import differently.
export default (db) => {
const Op = db.Sequelize.Op;
That method works to pull in the correct Op object. So there you go. Hopefully this nightmare issue helps someone else in the future.
I've created a database with two tables, Users and Points. A user can have many points and a point stores the ID of the user who sent it and the user who received it. I am trying to query for a table grouped by user showing the sum of the amounts of all their points, which is working querying raw in postgresql but not in sequelize.
Working in postgresql:
Creating the models with sequelize:
User.init(
{
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true,
},
telegram_id: {
type: DataTypes.INTEGER,
allowNull: false,
unique: true,
},
name: {
type: DataTypes.STRING,
allowNull: false,
},
},
{
tableName: "users",
sequelize: sequelize, // this bit is important
}
);
Point.init(
{
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true,
},
amount: {
type: DataTypes.INTEGER,
allowNull: false,
},
to_id: {
type: DataTypes.INTEGER,
allowNull: false,
},
from_id: {
type: DataTypes.INTEGER,
allowNull: false,
},
},
{
tableName: "points",
sequelize: sequelize, // this bit is important
}
);
User.hasMany(Point, {
sourceKey: "telegram_id",
foreignKey: "to_id",
as: "recievedPoints", // this determines the name in `associations`!
});
User.hasMany(Point, {
sourceKey: "telegram_id",
foreignKey: "from_id",
as: "sentPoints", // this determines the name in `associations`!
});
Point.belongsTo(User, {
foreignKey: "to_id",
targetKey: "telegram_id",
as: "toUser",
});
Point.belongsTo(User, {
foreignKey: "from_id",
targetKey: "telegram_id",
as: "fromUser",
});
Attempting to make same query with sequelize:
const points = await Point.findAll({
attributes: [
"users.name",
"points.to_id",
[Sequelize.fn("SUM", Sequelize.col("points.amount")), "points.amount"],
],
include: ["toUser"],
group: ["users.name", "points.to_id"],
});
Resulting error:
SequelizeDatabaseError: invalid reference to FROM-clause entry for table "users"
SQL generated by sequelize:
SELECT "users"."name", "points"."to_id", SUM("points"."amount") AS "points.amount", "toUser"."id" AS "toUser.id", "toUser"."telegram_id" AS "toUser.telegram_id", "toUser"."name" AS "toUser.name", "toUser"."createdAt" AS "toUser.createdAt", "toUser"."updatedAt" AS "toUser.updatedAt" FROM "points" AS "Point"
LEFT OUTER JOIN "users" AS "toUser" ON "Point"."to_id" = "toUser"."telegram_id" GROUP BY "users"."name", "points"."to_id";
RAW QUERY :
SELECT "users"."name", "points"."to_id", SUM("points"."amount") AS "points.amount", "toUser"."id" AS "toUser.id", "toUser"."telegram_id" AS "toUser.telegram_id", "toUser"."name" AS "toUser.name", "toUser"."createdAt" AS "toUser.createdAt", "toUser"."updatedAt" AS "toUser.updatedAt"
FROM "points" AS "Point"
LEFT OUTER JOIN "users" AS "toUser" ON "Point"."to_id" = "toUser"."telegram_id" GROUP BY "users"."name", "points"."to_id";
As per your raw query :
Change "users" to "toUser" every where
Change "points" to "Point" every where , like this :
const points = await Point.findAll({
attributes: [
"toUser.name",
"Point.to_id",
[Sequelize.fn("SUM", Sequelize.col("Point.amount")), "Point.amount"],
],
include: ["toUser"],
group: ["toUser.name", "Point.to_id"],
});
I am using sequelize to define my Model with postgres.
I have the following
#Options({
sequelize: db.main,
freezeTableName: true,
paranoid: true,
tableName: 'artist',
timestamps: true,
indexes: [{
unique: true,
fields: ['name'],
}],
})
#Attributes({
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
},
name: {
type: DataTypes.TEXT,
allowNull: false,
},
My Q is how do I get a custom error message when I try to create an artist with the same name as in DB. As per http://docs.sequelizejs.com/manual/tutorial/models-definition.html#validations
I mean I can use
validate: {
isIn: [['foo', 'bar']],
msg: 'Validation error for Artists w.r.t length',
}
But I cant seem to get a custom error message for Index on Model.
It throws generic error message lower(name) must be unique
How do I add custom error message for sequelize Index
"same name" means the unique index?
name: {
type: DataTypes.TEXT,
allowNull: false,
unique: {
msg: 'Validation error for Artists w.r.t length',
}
}
I am new developer and am trying to teach myself Sequelize and mysql with some little test projects. What I have right now is a little RPG team strength analyzer. I have a SQL table of Units, which has schema (id, name, elementOne, elementTwo) - integer, string, string, string.
For now, the elementOne and ElementTwo tables are both the same 18 string values because I couldn't figure out how to set up the Sequelize query with foreign keys refs to the same table (e.g. just 'elements').
Adding to the Unit table works fine on a local server, but breaks on Heroku ONLY when trying to add a third unit with the following error:
Error was: { SequelizeForeignKeyConstraintError: Cannot add or update a child
row: a foreign key constraint fails (`heroku_f4daeab1e260595`.`units`,
CONSTRAINT `units_ibfk_1` FOREIGN KEY (`id`) REFERENCES `elementtwos` (`id`)
ON DELETE CASCADE ON UPDATE CASCADE)
Here are all the tables and the relationship declarations.
const Unit = sequelize.define('unit', {
id: {
type: Sequelize.INTEGER,
allowNull: false,
unique: true,
primaryKey: true,
autoIncrement: true
},
name: {
type: Sequelize.STRING,
allowNull: false,
unique: false
},
image: {
type: Sequelize.STRING,
allowNull: true,
unique: false
},
elementOne: {
type: Sequelize.INTEGER,
allowNull: true,
references: {
model: Element,
key: 'id'
}
},
elementTwo: {
type: Sequelize.INTEGER,
allowNull: true,
defaultValue: 10001,
references: {
model: ElementTwo,
key: 'id'
}
}
});
const Element = sequelize.define('element', {
id: {
type: Sequelize.INTEGER,
allowNull: false,
unique: true,
primaryKey: true,
autoIncrement: true
},
name: {
type: Sequelize.STRING,
allowNull: false,
unique: false
}
});
const ElementTwo = sequelize.define('elementtwo', {
id: {
type: Sequelize.INTEGER,
allowNull: false,
unique: true,
primaryKey: true,
autoIncrement: true
},
name: {
type: Sequelize.STRING,
allowNull: false,
unique: false
}
});
After these are all loaded, I set up the following:
Unit.belongsTo(Element, {foreignKey: 'elementOne'});
Unit.belongsTo(ElementTwo, {foreignKey: 'elementTwo'});
ElementTwo.hasMany(Unit, {foreignKey: 'id'});
Element.hasMany(Unit, {foreignKey: 'id'});
And this is the query that Sequelize is doing (in a Unit.create({...}):
INSERT INTO `units`
(`id`,`name`,`image`,`elementOne`,`elementTwo`,`createdAt`,`updatedAt`) VALUES
(DEFAULT,'raichu','http://longimgurl.png',13,10001,'2017-06-14
12:57:54','2017-06-14 12:57:54');
If anyone can offer any advice it would be greatly appreciated.
this is mysql error and because you define foreign key constraint on you table and try to insert unavailable value in fk field that does not exit in target table,
check element and elementTwo table and make sure this values are available