Related
This is the result what I need to store in DB :
sellers : [{'test1'},{'test2'},{'test3'}]
And this is my model:
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define(
"User",
{
id: {
allowNull: false,
primaryKey: true,
autoIncrement: true,
type: DataTypes.INTEGER,
},
name: {
type: DataTypes.STRING,
allowNull: false,
},
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
},
password: {
type: DataTypes.STRING,
allowNull: false,
},
sellers: [
{
type: DataTypes.STRING,
allowNull: true,
},
],
},
{
timestamps: true,
defaultScope: {
attributes: {
exclude: ["password"],
},
},
scopes: {
withPassword: {
attributes: {},
},
},
indexes: [
{
unique: true,
fields: ["email"],
},
],
}
);
return User;
};
And the error is :
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near
sellers: [
{
type: DataTypes.ARRAY(DataTypes.STRING),
allowNull: true,
}
You need to slightly change your schema definition as,
sellers: {
type: DataTypes.ARRAY(DataTypes.JSON),
allowNull: true,
defaultValue: [{}],
get() {
const data = this.getDataValue('sellers');
const queryResponse = [];
data.forEach(seller => {
queryResponse.push(JSON.parse(seller));
});
return queryResponse;
},
set(seller) {
return this.setDataValue('sellers', JSON.stringify(seller));
}
},
I am trying to set reference from donorslist table to user table and requestblood table. Though the references columns(userid, requestbloodid) are getting added to the table, it is failing to insert the reference id 'requestbloodid' in the column and sets it to NULL.
I am using
Nodejs
mysql: 2.16.0 v
sequelize: 4.37.10 v
user.js model file:
const moment = require('moment');
module.exports = (sequelize, DataTypes) => {
const user = sequelize.define(
'user',
{
id: {
type: DataTypes.UUID,
primaryKey: true,
allowNull: false,
defaultValue: DataTypes.UUIDV4,
},
fullname: {
type: DataTypes.STRING(20),
allowNull: false,
},
gender: { type: DataTypes.CHAR(1), allowNull: false },
latitude: {
type: DataTypes.DECIMAL(20, 15),
allowNull: false,
validate: { min: -90, max: 90 },
},
longitude: {
type: DataTypes.DECIMAL(20, 15),
allowNull: false,
validate: { min: -180, max: 180 },
},
email: {
type: DataTypes.STRING(50),
allowNull: true,
},
isglobalcontactshared: { type: DataTypes.BOOLEAN, defaultValue: false },
createdAt: {
type: DataTypes.DATE,
get() {
return moment.utc(new Date(), 'DD-MMM-YYYY h:mm a').format('DD-MMM-YYYY h:mm a');
},
},
updatedAt: {
type: DataTypes.DATE,
defaultValue: null,
},
},
{
freezeTableName: true,
}
);
user.associate = function(models) {
user.belongsTo(models.contactdetails, {
onDelete: 'CASCADE',
hooks: true,
foreignKey: {
name: 'contactdetailid',
allowNull: false,
foreignKeyConstraint: true,
},
});
};
return user;
};
requestblood.js file:
const moment = require('moment');
module.exports = (sequelize, DataTypes) => {
const requestblood = sequelize.define(
'requestblood',
{
id: {
type: DataTypes.UUID,
primaryKey: true,
allowNull: false,
defaultValue: DataTypes.UUIDV4,
},
requestid: {
type: DataTypes.STRING(10),
allowNull: false,
},
latitude: {
type: DataTypes.DECIMAL(20, 15),
allowNull: false,
validate: { min: -90, max: 90 },
},
longitude: {
type: DataTypes.DECIMAL(20, 15),
allowNull: false,
validate: { min: -180, max: 180 },
},
locality: { type: DataTypes.STRING(20), allowNull: false },
city: { type: DataTypes.STRING, allowNull: false },
bloodtype: {
type: DataTypes.INTEGER,
allowNull: false,
isNumeric: true,
validate: { min: 1, max: 9 },
},
duedate: {
type: DataTypes.DATEONLY,
allowNull: false,
get() {
return moment.utc(this.getDataValue('duedate')).format('DD-MMM-YYYY');
},
},
unitsrequired: { type: DataTypes.INTEGER, isNumeric: true },
description: { type: DataTypes.STRING(500) },
requeststateid: { type: DataTypes.STRING, allowNull: false },
createdAt: {
type: DataTypes.DATE,
get() {
return moment.utc(new Date(), 'DD-MMM-YYYY h:mm a').format('DD-MMM-YYYY h:mm a');
},
},
updatedAt: {
type: DataTypes.DATE,
defaultValue: null,
},
},
{
freezeTableName: true,
}
);
requestblood.associate = function(models) {
requestblood.belongsTo(models.contactdetails, {
onDelete: 'CASCADE',
hooks: true,
foreignKey: {
name: 'contactdetailid',
allowNull: false,
foreignKeyConstraint: true,
},
});
};
/* requestblood.associate = function(models) {
requestblood.hasMany(models.donorslist, {
onDelete: 'CASCADE',
hooks: true,
foreignKey: {
name: 'requestbloodid',
allowNull: false,
foreignKeyConstraint: true,
},
});
}; */
return requestblood;
};
donorslist.js file
const moment = require('moment');
module.exports = (sequelize, DataTypes) => {
const donorslist = sequelize.define(
'donorslist',
{
id: {
type: DataTypes.UUID,
primaryKey: true,
allowNull: false,
defaultValue: DataTypes.UUIDV4,
},
fullname: {
type: DataTypes.STRING(20),
allowNull: false,
},
bloodgroup: { type: DataTypes.INTEGER, allowNull: false },
contactnumber: { type: DataTypes.STRING(13), allowNull: true },
willdonate: { type: DataTypes.BOOLEAN, defaultValue: false },
hasdonated: { type: DataTypes.BOOLEAN, defaultValue: false },
createdAt: {
type: DataTypes.DATE,
get() {
return moment.utc(new Date(), 'DD-MMM-YYYY h:mm a').format('DD-MMM-YYYY h:mm a');
},
},
updatedAt: {
type: DataTypes.DATE,
defaultValue: null,
},
},
{
freezeTableName: true,
}
);
donorslist.associate = function(models) {
donorslist.belongsTo(models.requestblood, {
onDelete: 'CASCADE',
hooks: true,
foreignKey: {
name: 'requestbloodid',
allowNull: false,
foreignKeyConstraint: true,
},
});
};
donorslist.associate = function(models) {
donorslist.belongsTo(models.user, {
onDelete: 'CASCADE',
hooks: true,
foreignKey: {
name: 'userid',
allowNull: false,
foreignKeyConstraint: true,
},
});
};
return donorslist;
};
When the below code is executed,
models.donorslist
.create({
fullname,
bloodgroup: bloodgrp,
contactnumber: contnum,
willdonate: req.body.willdonate,
userid: usrid,
requestbloodid: reqid,
updatedAt: null,
})
`
it returns the query as:
INSERT INTO `donorslist` (`id`,`fullname`,`bloodgroup`,`contactnumber`,`willdonate`,`hasdonated`,`createdAt`,`updatedAt`,`userid`) VALUES ('687888be-4381-460f-af62-46365a16fb40','sunil',4,'+123456789',true,false,'2019-01-10 07:00:12','2019-01-10 07:00:12','b93cfd73-a6ea-4825-91ad-8ded37418ca7');
Note the missing requestbloodid column. It somehow skips the requestbloodid column. I am facing this issue, after performing migrations. This was working fine with sequelize.sync(). If i uncomment the below code in requestblood.js file, then the referenceid 'contactdetailid' of requestblood table is set as NULL. So, i am unable to make a reference of belongsTo and hasMany from these two tables.
requestblood.associate = function(models) {
requestblood.hasMany(models.donorslist, {
onDelete: 'CASCADE',
hooks: true,
foreignKey: {
name: 'requestbloodid',
allowNull: false,
foreignKeyConstraint: true,
},
});
};
20181005120552-create-order-detail.js
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('OrderDetails', {
orderDetailId: {
type: Sequelize.INTEGER,
primaryKey: true,
allowNull: false,
autoIncrement: true,
},
orderId: {
type: Sequelize.INTEGER,
onDelete: 'CASCADE',
references: {
model: 'Orders',
key: 'orderId'
}
},
productName: {
type: Sequelize.STRING,
primaryKey: true,
allowNull: false,
},
count: {
type: Sequelize.INTEGER
},
orderDetailPrice: {
type: Sequelize.INTEGER,
onDelete: 'CASCADE',
references: {
model: 'Orders',
key: 'totalPrice'
}
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('OrderDetails');
}
};
20181005120522-create-order
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface
.createTable('Orders', {
orderId: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true,
allowNull: false
},
userId: {
type: Sequelize.STRING,
onDelete: 'CASCADE',
references: {
model: 'Users',
key: 'userId'
}
},
orderDate: {
type: Sequelize.DATE
},
totalPrice: {
type: Sequelize.INTEGER,
primaryKey: true,
allowNull: false,
},
orderState: {
type: Sequelize.STRING
},
shippingNumber: {
type: Sequelize.STRING
},
basicAddress: {
type: Sequelize.STRING
},
detailAddress: {
type: Sequelize.STRING
},
telNumber: {
type: Sequelize.INTEGER
},
phoneNumber: {
type: Sequelize.INTEGER
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('Orders');
}
};
When i executed script sequelize db:migrate, previous migration is without errors executed. in this level it returns error. I don't know how can i resolve this problem i guess it has something wrong.
ERROR: Failed to add the foreign key
constraint. Missing index for
constraint 'orderdetails_ibfk_2' in
the referenced table 'orders'
This is error message. I wanna connect files OrderDetails.orderDetailPrice and Orders.totalPrice.
Thanks.
As reported here, it seems that Sequelize has some issues with references to composite keys.
However, by exploiting the Sequelize query execution you can workaround you problem. In you case you can perform the following mysql query:
ALTER TABLE `db_test`.`OrderDetails` ADD CONSTRAINT `fk_order_detailes_orders`
FOREIGN KEY (`orderId` , `orderDetailId`)
REFERENCES `db_test `.`orders`(`orderId` , `totalPrice`);
So your create-order-detail migration file becomes the following:
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('OrderDetails', {
orderDetailId: {
type: Sequelize.INTEGER.UNSIGNED,
primaryKey: true,
allowNull: false,
autoIncrement: true,
},
orderId: {
type: Sequelize.INTEGER,
allowNull: false,
},
productName: {
type: Sequelize.STRING,
primaryKey: true,
allowNull: false,
},
count: {
type: Sequelize.INTEGER,
},
orderDetailPrice: {
type: Sequelize.INTEGER,
allowNull: false,
},
createdAt: {
allowNull: false,
type: Sequelize.DATE,
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE,
},
})
.then(() => {
return queryInterface.sequelize.query('ALTER TABLE `OrderDetails` ADD ' +
'CONSTRAINT `fk_order_details_orders` FOREIGN KEY (`orderId`, `orderDetailPrice`) REFERENCES ' +
'Orders(`orderId`, `totalPrice`)');
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('OrderDetails', null);
},
};
Giordano,
I defined this way the code is below. Let me know why this code can be migrated? primary key and unique key both keys are written though..
create-order-detail.js
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('OrderDetails', {
(...),
productName: {
type: Sequelize.STRING,
primaryKey: true,
// allowNull: false
unique: true
},
count: {
type: Sequelize.INTEGER
},
orderDetailPrice: {
type: Sequelize.INTEGER,
onDelete: 'CASCADE',
// references: {
// model: 'Orders',
// key: 'totalPrice'
// }
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
})
.then(() => {
queryInterface.addConstraint('OrderDetails', ['orderDetailPrice'], {
type: 'foreign key',
references: {
name: 'orderdetails_ibfk_2',
table: 'Orders',
field: 'totalPrice'
},
})
})
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('OrderDetails');
}
};
Here is my problem:
Table WO -> sparepart_request -> sparepart.
A work order have several sparepart and sparepart can belong to several WO.
This is my code in wo.js (sequelize model)
models.sparepart.belongsToMany(models.wo, { as: 'SPWO', through: 'sparepart_request', foreignKey: 'codSparePart' });
This is my code in sparepart.js (sequelize model).
models.sparepart.belongsToMany(models.wo, { as: 'SPWO', through: 'sparepart_request', foreignKey: 'codSparePart' });
In sparepart_request there is nothing about associations. I've followed the next instructions Sequelize
In my query I have the next code:
exports.readDetailWO = function (req, res) {
models.wo.findAll({
attributes: ['codWO'], // attributes: ['id', 'codWO', 'codSparePart', 'quantity', 'date_request', 'date_reception', 'details', 'codUser', 'received'],
raw: true,
where: {
codWO: req.params.codWO
},
include: [{
model: models.sparepart,
attributes: ['codSparePart', 'name', 'description', 'codManufacturer', 'image_uri', 'stock'],
paranoid: false,
required: false,
as: 'SPWO'
}]
}).then(sparePart => {
if (!sparePart) {
res.status(404);
res.send({
success: false,
message: 'Spare Part not found. ' + req.params.codWO,
data: sparePart
});
} else if (sparePart) {
res.json({
success: true,
message: 'Spare Part found.',
data: sparePart
});
}
}).catch(function (error) {
logger.error(JSON.stringify(error));
res.json({
message: 'Query not successful and error has occured reading',
error: error,
stackError: error.stack
});
return res.status(500);
});
};
But the server's response (using PostMan) is the following:
{
"message": "Query not successful and error has occured reading",
"error": {
"name": "SequelizeEagerLoadingError"
},
"stackError": "SequelizeEagerLoadingError: sparepart is not associated to wo!\n
AS I have been able to read here that maybe the problem that is my primaryKeys are not name id, but now I can change these names...
Where is the problem? Thanks in advance for your help.
Model sparepart_request.js
module.exports = function (sequelize, DataTypes) {
var sparepart_request = sequelize.define('sparepart_request', {
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true
},
codWo: {
type: DataTypes.STRING(20),
allowNull: false,
foreignKey: {
model: 'wo',
key: 'codWO'
}
},
codSparePart: {
type: DataTypes.STRING(30),
allowNull: false,
references: {
model: 'sparepart',
key: 'codSparePart'
}
},
quantity: {
type: DataTypes.FLOAT,
allowNull: true
},
date_request: {
type: DataTypes.DATEONLY,
allowNull: true
},
date_reception: {
type: DataTypes.DATEONLY,
allowNull: true
},
details: {
type: DataTypes.TEXT,
allowNull: true
},
codUser: {
type: DataTypes.STRING(20),
allowNull: false,
references: {
model: 'user',
key: 'codUser'
}
},
received: {
type: DataTypes.INTEGER(1),
allowNull: false
}
}, {
tableName: 'sparepart_request',
timestamps: false
});
/* sparepart_request.associate = function (models) {
models.sparepart_request.hasMany(models.sparepart, {foreignKey: 'codSparePart', targetKey: 'codSparePart'});
}; */
return sparepart_request;
};
Model wo.js:
/* jshint indent: 1 */
module.exports = function (sequelize, DataTypes) {
var wo = sequelize.define('wo', {
codWO: {
type: DataTypes.STRING(20),
allowNull: false,
primaryKey: true
},
codUser: {
type: DataTypes.STRING(20),
allowNull: false,
references: {
model: 'user',
key: 'codUser'
}
},
codOriginator: {
type: DataTypes.STRING(20),
allowNull: true,
references: {
model: 'user',
key: 'codUser'
}
},
capture_date: {
type: DataTypes.DATE,
allowNull: false
},
active: {
type: DataTypes.INTEGER(1),
allowNull: false
},
codType: {
type: DataTypes.CHAR(3),
allowNull: false,
references: {
model: 'type',
key: 'codType'
}
},
date: {
type: DataTypes.DATEONLY,
allowNull: false
},
title: {
type: DataTypes.STRING(255),
allowNull: true
},
date_finish: {
type: DataTypes.DATEONLY,
allowNull: true
},
codStatus: {
type: DataTypes.STRING(10),
allowNull: false,
references: {
model: 'status',
key: 'codStatus'
}
},
hours_planned: {
type: DataTypes.FLOAT,
allowNull: true
},
codElement: {
type: DataTypes.INTEGER(11),
allowNull: true,
references: {
model: 'element',
key: 'codElement'
}
},
Security: {
type: DataTypes.INTEGER(1),
allowNull: true,
defaultValue: '0'
},
codEquipment: {
type: DataTypes.STRING(20),
allowNull: false,
references: {
model: 'equipment',
key: 'codEquipment'
}
},
codProject: {
type: DataTypes.INTEGER(11),
allowNull: false,
references: {
model: 'project',
key: 'id'
}
},
codTestRoom: {
type: DataTypes.STRING(10),
allowNull: false,
references: {
model: 'testroom',
key: 'codTestRoom'
}
}
}, {
tableName: 'wo',
timestamps: false
});
wo.associate = function (models) {
models.wo.belongsTo(models.wo_operation, {
as: 'wo_operation',
foreignKey: {
name: 'codWO',
allowNull: false
},
targetKey: 'codWO'
});
models.wo.belongsTo(models.dailyinfo_detail, {
as: 'dailyInfo',
foreignKey: {
name: 'codWO',
allowNull: false
},
targetKey: 'codWO'
});
models.wo.hasOne(models.wo_corrective, {
as: 'wo_corrective',
foreignKey: {
name: 'codWO',
allowNull: false
},
targetKey: 'codWO'
});
models.wo.hasOne(models.wo_preventive, {
as: 'wo_preventive',
foreignKey: {
name: 'codWO',
allowNull: false
},
targetKey: 'codWO'
});
models.wo.belongsToMany(models.sparepart_request, { as: 'WOSP', through: 'sparepart_request', foreignKey: 'codWO', otherKey: 'codSparePart' });
};
return wo;
};
Model sparepart.js
/* jshint indent: 1 */
module.exports = function (sequelize, DataTypes) {
var sparepart = sequelize.define('sparepart', {
codSparePart: {
type: DataTypes.STRING(30),
allowNull: false,
primaryKey: true,
references: {
model: 'sparepart_request',
key: 'codSparePart'
}
},
name: {
type: DataTypes.STRING(45),
allowNull: true
},
description: {
type: DataTypes.TEXT,
allowNull: true
},
available: {
type: DataTypes.INTEGER(1),
allowNull: false,
defaultValue: '1'
},
codManufacturer: {
type: DataTypes.INTEGER(11),
allowNull: false,
references: {
model: 'manufacturer',
key: 'codManufacturer'
}
},
stock: {
type: DataTypes.INTEGER(10),
allowNull: true
},
image_uri: {
type: DataTypes.STRING(500),
allowNull: true
},
codProject: {
type: DataTypes.INTEGER(11),
allowNull: true,
references: {
model: 'project',
key: 'id'
}
},
price: {
type: DataTypes.FLOAT,
allowNull: false
}
}, {
tableName: 'sparepart',
timestamps: false
});
sparepart.associate = function (models) {
models.sparepart.belongsTo(models.manufacturer, {
foreignKey: 'codManufacturer',
targetKey: 'codManufacturer'
});
models.sparepart.belongsToMany(models.wo, { as: 'SPWO', through: 'sparepart_request', foreignKey: 'codSparePart', otherKey: 'codWO' });
};
return sparepart;
};
Here you can find my code, the three models and the query. at the moment I'm using postman I don't have anything in the frontEnd.
Here is one solution:
Remove id from sparepart_request.
Include the next code in sparepart_request:
sparepart_request.associate = function (models) {
models.sparepart_request.hasMany(models.sparepart, {foreignKey: 'codSparePart', targetKey: 'codSparePart'});
models.sparepart_request.hasMany(models.wo, {foreignKey: 'codWO', targetKey: 'codWO'});
};
Is it the correct way to do?, Apparently it is working...
How do I define a unique index on a combination of columns in sequelize. For example I want to add a unique index on user_id, count and name.
var Tag = sequelize.define('Tag', {
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true
},
user_id: {
type: DataTypes.INTEGER(11),
allowNull: false,
},
count: {
type: DataTypes.INTEGER(11),
allowNull: true
},
name: {
type: DataTypes.STRING,
allowNull: true,
})
You can refer to this doc http://docs.sequelizejs.com/en/latest/docs/models-definition/#indexes
You will need to change your definition like shown below and call sync
var Tag = sequelize.define('Tag', {
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true
},
user_id: {
type: DataTypes.INTEGER(11),
allowNull: false,
},
count: {
type: DataTypes.INTEGER(11),
allowNull: true
},
name: {
type: DataTypes.STRING,
allowNull: true,
}
},
{
indexes: [
{
unique: true,
fields: ['user_id', 'count', 'name']
}
]
});
I have same issue to applied composite unique constraint to multiple
columns but nothing work with Mysql, Sequelize(4.10.2) and NodeJs
8.9.4 finally I fixed through following code.
queryInterface.createTable('actions', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
system_id: {
type: Sequelize.STRING,
unique: 'actions_unique',
},
rule_id: {
type: Sequelize.STRING,
unique: 'actions_unique',
},
plan_id: {
type: Sequelize.INTEGER,
unique: 'actions_unique',
}
}, {
uniqueKeys: {
actions_unique: {
fields: ['system_id', 'rule_id', 'plan_id']
}
}
});
If the accepted one is not working then try the below code. It worked for me in my case rather the accepted one.
var Tag = sequelize.define('Tag', {
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true
},
user_id: {
type: DataTypes.INTEGER(11),
allowNull: false,
unique: 'uniqueTag',
},
count: {
type: DataTypes.INTEGER(11),
allowNull: true,
unique: 'uniqueTag',
},
name: {
type: DataTypes.STRING,
allowNull: true,
unique: 'uniqueTag',
}
});
I tried to create an index on a single column.
This worked for me. Hope this helps.
Model
module.exports = (sequelize, DataTypes) => {
const Tag = sequelize.define(
"Tag",
{
name: { type: DataTypes.STRING, unique: true },
nVideos: DataTypes.INTEGER
},
{
indexes: [
{
unique: true,
fields: ["name"]
}
]
}
);
return Tag;
};
Migration
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable(
"Tags",
{
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
name: {
type: Sequelize.STRING,
unique: "unique_tag"
},
nVideos: { type: Sequelize.INTEGER },
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
},
{
uniqueKeys: {
unique_tag: {
customIndex: true,
fields: ["name"]
}
}
}
);
},
down: queryInterface => {
return queryInterface.dropTable("Tags");
}
};
I prefer sequelize sync method with composite unique, If not passing indexes name u will get a error as below on adding many indexes in index array.
error: SequelizeDatabaseError: Identifier name 'LONG_NAME' is too long
module.exports = function (sequelize: any, DataTypes: any) {
return sequelize.define('muln_user_goals_transaction', {
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
autoIncrement: true,
primaryKey: true,
},
name: {
type: DataTypes.STRING(),
allowNull: false,
},
email: {
type: DataTypes.STRING(),
allowNull: false,
},
phone: {
type: DataTypes.STRING(),
allowNull: false,
},
amount: {
type: DataTypes.INTEGER(8),
allowNull: false
},
deleted: {
type: DataTypes.BOOLEAN,
defaultValue: false,
},
}, {
tableName: 'muln_user_goals_transaction',
timestamps: false,
indexes: [
{
name: 'unique_index',
unique: true,
fields: ['name', 'email', 'phone', 'amount', 'deleted']
}
],
defaultScope: {
where: {
deleted: false
}
}
});
};
Sequelize composite unique (manual)
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('Model', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
fieldOne: {
type: Sequelize.INTEGER,
unique: 'uniqueTag',
allowNull: false,
references: {
model: 'Model1',
key: 'id'
},
onUpdate: 'cascade',
onDelete: 'cascade'
},
fieldsTwo: {
type: Sequelize.INTEGER,
unique: 'uniqueTag',
allowNull: false,
references: {
model: 'Model2',
key: 'id'
},
onUpdate: 'cascade',
onDelete: 'cascade'
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
})
.then(function() {
return queryInterface.sequelize.query(
'ALTER TABLE `UserFriends` ADD UNIQUE `unique_index`(`fieldOne`, `fieldTwo`)'
);
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('Model');
}
};