Sequelize throwing error "must be unique" - mysql

I am using Sequelize with my mysql database and have a many to many relationship with a CostumerDriverTransaction model as a through table
when I try to create a row form this table I get this error "message": "driverId must be unique"
CostumerDriverTransaction Model
const CostumerDriverTransaction = sequelize.define('CostumerDriverTransaction', {
costumerId: {
type:DataTypes.INTEGER,
},
driverId: {
type:DataTypes.INTEGER,
},
restaurantId: {
type:DataTypes.INTEGER,
},
orderId: DataTypes.INTEGER,
transactionId: {
type:DataTypes.INTEGER,
primaryKey:true,
},
},{});
and this the association:
index.js
db.user.belongsToMany(db.driver,{
through:db.costumerDriverTransaction,
foreignKey:{
name:'costumerId'
}
});
db.driver.belongsToMany(db.user,{
through:db.costumerDriverTransaction,
foreignKey:{
name:'driverId'
}
});
db.user.hasMany(db.costumerDriverTransaction,{
foreignKey:{
name:'costumerId'
}
});
db.driver.hasMany(db.costumerDriverTransaction,{
foreignKey:{
name:'driverId'
}
});
db.costumerDriverTransaction.belongsTo(db.user,{
foreignKey:{
name:'costumerId'
}
});
db.costumerDriverTransaction.belongsTo(db.driver,{
foreignKey:{
name:'driverId'
}
});
what's the problem please ?

As error indicates, you need to set driverId to be unique, that is:
const CostumerDriverTransaction = sequelize.define('CostumerDriverTransaction', {
costumerId: {
type:DataTypes.INTEGER,
},
driverId: {
type:DataTypes.INTEGER,
unique: true
},
restaurantId: {
type:DataTypes.INTEGER,
},
orderId: DataTypes.INTEGER,
transactionId: {
type:DataTypes.INTEGER,
primaryKey:true,
},
},{});

Most of the columns do not need to be specified in your define and will be create automatically, such at the primary keys and relationship fields. If you would like to override them, you can specify them in the column definition (this is only really notable because transactionId in your example would become id when autogenerated.
Here we create models for each of your objects and then define all the different relationships between them. Because the relationship table is a "super" many-to-many by having it's own primary key instead of a composite you can query from it or any of the other models "through" it.
If you don't want the createdAt and updatedAt columns on a table pass timestamps: false, into the options for sequelize.define().
// your other models
const User = sequelize.define('User', {}, {});
const Driver = sequelize.define('Driver', {}, {});
const Restaurant = sequelize.define('Restaurant', {}, {});
const Order = sequelize.define('Order', {}, {});
// the relational table, note that leaving off the primary key will use `id` instead of transactionId
const CostumerDriverTransaction = sequelize.define('CostumerDriverTransaction', {}, {});
// relate the transaction to the other
CostumerDriverTransaction.belongsTo(User, { foreignKey: 'customerId' });
CostumerDriverTransaction.belongsTo(Driver, { foreignKey: 'driverId' });
CostumerDriverTransaction.belongsTo(Restaurant, { foreignKey: 'restaurantId' });
CostumerDriverTransaction.belongsTo(Order, { foreignKey: 'orderId' });
// relate the models to the transactions
User.hasMany(CostumerDriverTransaction, { as: 'transactions', foreignKey: 'customerId' });
// relate models to other models through transactions
User.hasMany(Driver, { as: 'drivers', through: 'CostumerDriverTransaction', foreignKey: 'customerId', otherKey: 'driverId' });
User.hasMany(Restaurant, { as: 'restaurants', through: 'CostumerDriverTransaction', foreignKey: 'customerId', otherKey: 'restaurantId' });
User.hasMany(Order, { as: 'orders', through: 'CostumerDriverTransaction', foreignKey: 'customerId', otherKey: 'orderId' });
// Drivers
Driver.hasMany(CostumerDriverTransaction, { foreignKey: 'driverId' });
Driver.hasMany(User, { as: 'customers', through: 'CostumerDriverTransaction', foreignKey: 'driverId', otherKey: 'customerId' });
Driver.hasMany(Restaurant, { as: 'restaurants', through: 'CostumerDriverTransaction', foreignKey: 'driverId', otherKey: 'restaurantId' });
Driver.hasMany(Order, { as: 'orders', through: 'CostumerDriverTransaction', foreignKey: 'driverId', otherKey: 'orderId' });
// Restaurants
Restaurant.hasMany(CostumerDriverTransaction, { foreignKey: 'restaurantId' });
Restaurant.hasMany(Driver, { as: 'drivers', through: 'CostumerDriverTransaction', foreignKey: 'restaurantId', otherKey: 'driverId' });
Restaurant.hasMany(User, { as: 'customers', through: 'CostumerDriverTransaction', foreignKey: 'restaurantId', otherKey: 'customerId' });
Restaurant.hasMany(Order, { as: 'orders', through: 'CostumerDriverTransaction', foreignKey: 'restaurantId', otherKey: 'orderId' });
// Orders
Order.hasMany(CostumerDriverTransaction, { foreignKey: 'orderId' });
Order.hasMany(Driver, { as: 'drivers', through: 'CostumerDriverTransaction', foreignKey: 'orderId', otherKey: 'driverId' });
Order.hasMany(User, { as: 'customers', through: 'CostumerDriverTransaction', foreignKey: 'orderId', otherKey: 'customerId' });
Order.hasMany(Restaurant, { as: 'restaurants', through: 'CostumerDriverTransaction', foreignKey: 'orderId', otherKey: 'restaurantId' });
This will create models with primary key and relationship columns of:
// User
{
id: primary key,
createdAt: create date,
updatedAt: update date,
}
// Driver
{
id: primary key,
createdAt: create date,
updatedAt: update date,
}
// Restaurant
{
id: primary key,
createdAt: create date,
updatedAt: update date,
}
// Order
{
id: primary key,
createdAt: create date,
updatedAt: update date,
}
// Transaction
{
id: primary key,
userId: relationship to User,
driverId: relationship to Driver,
restaurantId: relationship to Restaurant,
orderId: relationship to Order,
createdAt: create date,
updatedAt: update date,
}

Related

How to exclude associated table from findAll method in sequelize JS?

I have 3 tables, course,groups and students. Each course has multiple groups and each groups have multiple students. I want to select courses and its students but when I use findAll method its displays groups too like [{courseName,courseCode,groups:[....,students:[...]]. I just want [{courseName,courseCode,students:[...]}}] .
How can i exclude group table in findAll method?
These are my tables:
Course table:
module.exports = (sequelize, DataTypes) => {
class course extends Model {
static associate(models) {
const { group } = models;
this.hasMany(group, {
foreignKey: "cid",
});
}
}
course.init(
{
cid: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
allowNull: false,
},
cname: DataTypes.STRING,
ccode: DataTypes.INTEGER,
},
{
indexes: [
{
unique: true,
fields: ["cname", "ccode"],
},
],
sequelize,
modelName: "course",
}
);
return course;
};
Group table:
module.exports = (sequelize, DataTypes) => {
class group extends Model {
static associate(models) {
const { teacher, studentgroup, student, subject, course } = models;
this.hasMany(subject);
this.belongsTo(course, {
onDelete: "CASCADE",
foreignKey: "cid",
});
this.belongsTo(teacher, {
onDelete: "CASCADE",
foreignKey: "tid",
});
this.belongsToMany(student, {
through: studentgroup,
foreignKey: "gid",
onDelete: "CASCADE",
});
}
}
group.init(
{
gid: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
allowNull: false,
},
gno: DataTypes.STRING,
},
{
sequelize,
modelName: "group",
timestamps: false,
}
);
return group;
};
Student table
module.exports = (sequelize, DataTypes) => {
class student extends Model {
static associate(models) {
const { group, studentgroup, attendance, user, studentparent, parent } =
models;
this.belongsToMany(parent, {
through: studentparent,
foreignKey: "sid",
});
this.belongsTo(user, {
foreignKey: "uid",
});
this.belongsToMany(group, {
through: studentgroup,
foreignKey: "sid",
onDelete: "CASCADE",
});
this.hasMany(attendance, {
foreignKey: "sid",
});
}
}
student.init(
{
sid: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
allowNull: false,
},
name: DataTypes.STRING,
lastname: DataTypes.STRING,
},
{
sequelize,
modelName: "student",
}
);
return student;
};
And this is my query:
await course.findAll({
required: true,
attributes: ["cname", "ccode"],
include: [
{
required: true,
model: models["group"],
include: [
{
model: student,
required: true,
},
],
},
],
});

Sequelize: Wrong column names on junction table columns

I have a MySQL database where everything is in snake_case. I have two models with many-to-many relationship (RoomBooking and User), and one manually-defined model (called MeetingGuest) that acts as their junction table (among other things). The problem is, Sequelize keeps generating queries with PascalCase column and table names for this junction model.
MeetingGuest is generated using sequelize-cli, and tweaked to become like so:
const { Model } = require('sequelize')
module.exports = (sequelize, DataTypes) => {
class MeetingGuest extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
}
}
MeetingGuest.init(
{
room_booking_id: {
type: DataTypes.INTEGER,
references: {
model: 'RoomBooking',
key: 'id',
},
},
user_id: {
type: DataTypes.INTEGER,
references: {
model: 'User',
key: 'id',
},
},
status: DataTypes.STRING,
check_in: DataTypes.BOOLEAN,
},
{
sequelize,
modelName: 'MeetingGuest',
tableName: 'meeting_guests',
createdAt: 'created_at',
updatedAt: 'updated_at',
},
)
return MeetingGuest
}
The query it generates is like this:
SELECT
MeetingGuest.RoomBookingId, -- `room_booking_id` is never aliased into RoomBookingId
-- Other selected columns...
FROM `users` AS `User`
INNER JOIN `meeting_guests` AS `MeetingGuest`
ON `User`.`id` = `MeetingGuest`.`UserId` AND `MeetingGuest`.`RoomBookingId` = 1;
Defining the foreign keys explicitly is the key.
I went from
modelA.belongsToMany(modelB,
{ through: associativeTable }
);
modelB.belongsToMany(modelA,
{ through: associativeTable }
);
to
modelA.belongsToMany(modelB,
{ through: associativeTable, foreignKey: 'modelA_id' }
);
modelB.belongsToMany(modelA,
{ through: associativeTable, foreignKey: 'modelB_id' }
);
And now everything is peachy
Looks like I have to add foreignKey and otherKey to the model to be associated with. In my case, it's RoomBooking (not the join table). Like this:
const { Model } = require('sequelize')
const User = require('./User')
module.exports = (sequelize, DataTypes) => {
class RoomBooking extends Model {
static associate(models) {
// define association here
this.belongsTo(models.Room, {
foreignKey: 'room_id',
})
this.belongsTo(models.User, {
foreignKey: 'user_id',
as: 'host',
})
this.belongsToMany(models.User, {
through: models.MeetingGuest,
foreignKey: 'room_booking_id',
otherKey: 'user_id',
as: 'guests',
})
}
}
RoomBooking.init(
{
user_id: {
type: DataTypes.INTEGER,
references: {
model: 'User',
key: 'id',
},
},
room_id: DataTypes.INTEGER,
// ...other fields
},
{
sequelize,
modelName: 'RoomBooking',
tableName: 'room_bookings',
createdAt: 'created_at',
updatedAt: 'updated_at',
},
)
return RoomBooking
}

SequelizeJS Eager Loading two identical N:M models one returns data other does not

I have one model Link and two other Models Overlay & Tracker. Both have many to many relationship with Link model. The data is in MySQL database.
Overlay & Tracker uses identical association with Link yet when I try to eager load them using sequlize query, Tracker values are always null (returns as empty array).
For example:
Consider this example query.
const result = await Link.findAndCountAll({
where: {
userId: req.user.id
},
limit: limit,
offset: offset,
order: [
['createdAt', 'DESC']
],
include: [
{model: Tracker, as: 'trackers'},
{model: Overlay, as: 'overlays'}
]
});
The returned result includes overlays correctly but trackers is always empty array. I am really puzzled because both models are identical in associations.
Models
Link.js
'use strict';
module.exports = (sequelize, DataTypes) => {
const Link = sequelize.define('Link', {
name: DataTypes.STRING,
// ... removed for simplicity
}
}, {
freezeTableName: true,
tableName: 'links'
});
Link.associate = function(models) {
// associations can be defined here
Link.belongsTo(models.User, {
as: 'user',
foreignKey: 'userId'
});
Link.belongsToMany(models.Overlay, {
as: 'overlays',
through: models.LinkOverlays,
foreignKey: 'linkId',
targetKey: 'id',
});
Link.belongsToMany(models.Tracker, {
as: 'trackers',
through: models.LinkTrackers,
foreignKey: 'trackerId',
targetKey: 'id',
});
};
return Link;
};
Overlay.js
'use strict';
module.exports = (sequelize, DataTypes) => {
const Overlay = sequelize.define('Overlay', {
name: DataTypes.STRING(100),
// ... removed for simplicity
}, {
freezeTableName: true,
tableName: 'overlays'
});
Overlay.associate = function(models) {
// associations can be defined here
Overlay.belongsTo(models.User, {
foreignKey: 'userId'
});
Overlay.belongsToMany(models.Link, {
as: 'links',
through: models.LinkOverlays,
foreignKey: 'overlayId',
targetKey: 'id'
});
};
return Overlay;
};
Tracker.js
'use strict';
module.exports = (sequelize, DataTypes) => {
const Tracker = sequelize.define('Tracker', {
name: DataTypes.STRING(100),
// ...
}, {
freezeTableName: true,
timestamps: false,
tableName: 'trackers'
});
Tracker.associate = function(models) {
Tracker.belongsTo(models.User, {
foreignKey: 'userId'
});
Tracker.belongsToMany(models.Link, {
as: 'links',
through: models.LinkTrackers,
foreignKey: 'trackerId',
targetKey: 'id'
});
};
return Tracker;
};
Observations:
The created SQL query also seems to be identical for both associated models. Here is the resulted SQL of the given query
SELECT `Link`.*,
`trackers`.`id` AS `trackers.id`,
`trackers`.`createdat` AS `trackers.createdAt`,
`trackers`.`name` AS `trackers.name`,
`trackers`.`vendor` AS `trackers.vendor`,
`trackers`.`vendortrackerid` AS `trackers.vendorTrackerId`,
`trackers`.`userid` AS `trackers.userId`,
`trackers->LinkTrackers`.`linkid` AS `trackers.LinkTrackers.linkId`,
`trackers->LinkTrackers`.`trackerid` AS `trackers.LinkTrackers.trackerId`
,
`overlays`.`id` AS `overlays.id`,
`overlays`.`name` AS `overlays.name`,
`overlays`.`type` AS `overlays.type`,
`overlays`.`config` AS `overlays.config`,
`overlays`.`userid` AS `overlays.userId`,
`overlays`.`createdat` AS `overlays.createdAt`,
`overlays`.`updatedat` AS `overlays.updatedAt`,
`overlays->LinkOverlays`.`linkid` AS `overlays.LinkOverlays.linkId`,
`overlays->LinkOverlays`.`overlayid` AS `overlays.LinkOverlays.overlayId`
FROM (SELECT `Link`.`id`,
`Link`.`name`,
`Link`.`originalurl`,
`Link`.`code`,
`Link`.`type`,
`Link`.`userid`,
`Link`.`hitcount`,
`Link`.`opengraph`,
`Link`.`createdat`,
`Link`.`updatedat`
FROM `links` AS `Link`
WHERE `Link`.`userid` = 1
ORDER BY `Link`.`createdat` DESC
LIMIT 0, 10) AS `Link`
LEFT OUTER JOIN ( `link_trackers` AS `trackers->LinkTrackers`
INNER JOIN `trackers` AS `trackers`
ON `trackers`.`id` =
`trackers->LinkTrackers`.`trackerid`)
ON `Link`.`id` = `trackers->LinkTrackers`.`trackerid`
LEFT OUTER JOIN ( `link_overlays` AS `overlays->LinkOverlays`
INNER JOIN `overlays` AS `overlays`
ON `overlays`.`id` =
`overlays->LinkOverlays`.`overlayid`)
ON `Link`.`id` = `overlays->LinkOverlays`.`linkid`
ORDER BY `Link`.`createdat` DESC;
More Information
Below are two relational table model
LinkOverlays.js
'use strict';
module.exports = (sequelize, DataTypes) => {
const LinkOverlays = sequelize.define('LinkOverlays', {
linkId: {
type: DataTypes.INTEGER,
primaryKey: true,
unique: 'linkIdOverlayIdComposite'
},
overlayId: {
type: DataTypes.INTEGER,
primaryKey: true,
unique: 'linkIdOverlayIdComposite'
}
}, {
freezeTableName: true,
timestamps: false,
tableName: 'link_overlays'
});
LinkOverlays.associate = function(models) {
// associations can be defined here
LinkOverlays.belongsTo(models.Link, {
foreignKey: 'linkId',
through: models.LinkOverlays,
targetKey: 'id'
});
// associations can be defined here
LinkOverlays.belongsTo(models.Overlay, {
foreignKey: 'overlayId',
through: models.LinkOverlays,
targetKey: 'id'
});
};
return LinkOverlays;
};
LinkTrackers.js
'use strict';
module.exports = (sequelize, DataTypes) => {
const LinkTrackers = sequelize.define('LinkTrackers', {
linkId: {
type: DataTypes.INTEGER,
primaryKey: true,
unique: 'linkIdTrackerIdComposite'
},
trackerId: {
type: DataTypes.INTEGER,
primaryKey: true,
unique: 'linkIdTrackerIdComposite'
}
}, {
freezeTableName: true,
timestamps: false,
tableName: 'link_trackers'
});
LinkTrackers.associate = function(models) {
LinkTrackers.belongsTo(models.Link, {
foreignKey: 'linkId',
through: models.LinkTrackers,
targetKey: 'id'
});
LinkTrackers.belongsTo(models.Tracker, {
foreignKey: 'trackerId',
through: models.LinkTrackers,
targetKey: 'id'
});
};
return LinkTrackers;
};
I have tried many hours to track down the issue but failed. The most puzzling is that one is working (Overlay) and other is not (Tracker)
In your
link.js
Link.belongsToMany(models.Overlay, {
as: 'overlays',
through: models.LinkOverlays,
foreignKey: 'linkId',
targetKey: 'id',
});
Link.belongsToMany(models.Tracker, {
as: 'trackers',
through: models.LinkTrackers,
foreignKey: 'trackerId', // should be linkId
targetKey: 'id',
});
the relation with LinkOverlays is via linkId but the relation with LinkTrackers is via trackerId it should be linkId as well

graphql multiple associations

I have the following models in sequelize
User
User.associate = models => {
User.hasMany(models.Schedule, {
onDelete: 'CASCADE',
foreignKey: 'patient_id',
sourceKey: 'id',
as: 'patient'
});
User.hasMany(models.Schedule, {
onDelete: 'CASCADE',
foreignKey: 'professional_id',
sourceKey: 'id',
as: 'professional'
});
};
Schedule
Schedule.associate = models => {
Schedule.belongsTo(models.User, {
foreignKey: 'patient_id',
targetKey: 'id',
as: 'patient'
});
};
Schedule.associate = models => {
Schedule.belongsTo(models.User, {
foreignKey: 'professional_id',
targetKey: 'id',
as: 'professional'
});
};
And the following schemas in graphql
user
type User {
id: ID!
schedules1: [Schedule] #relation(name: "patient")
schedules2: [Schedule] #relation(name: "professional")
}
schedule
type Schedule {
id: ID!
date : Date
patient: User! #relation(name: "patient")
professional: User! #relation(name: "professional")
}
but when try a query of users with schedules like this
{
users{
id
name
schedules1{
id
}
}
}
i got the following result
{
"data": {
"users": [
{
"id": "1",
"name": "Gregorio",
"schedules1": null
},
...
My question is, how i can model multiple associations in graphql, i tried the anotation #relation without success.
noob mistake... i forgot to add the resolver to the relations.
User: {
patient: async(user, args, { models }) =>
await models.Schedule.findAll({
where: {
patient_id: user.id,
},
}),
professional: async(user, args, { models }) =>
await models.Schedule.findAll({
where: {
professional_id: user.id,
},
})
},

Sequelize Query - Finding records based on many-to-many table and parent table

Given the following sequelize models:
var User = db.define('user', {
name: Sequelize.STRING
});
var Group = db.define('group', {
name: Sequelize.STRING,
public : { type: Sequelize.BOOLEAN, defaultValue: true }
});
Group.belongsToMany(User, { as: 'specialUsers', through: 'user_groups', foreignKey: 'group_id' });
User.belongsToMany(Group, { through: 'user_groups', foreignKey: 'user_id' });
How would I go about finding the Groups for a through the Groups model where the Groups returned should be those where the user has a record in the many to many table -- or -- the group is a public group?
I've tried something like this:
return Group.findAll({
attributes: ['name', 'public'],
include: [{
model: User,
as: 'specialUsers',
where: {
$or : [
{name: 'Neill'},
Sequelize.literal('"group"."public" = true')
]
}
}]
});
return Group.findAll({
attributes: ['name', 'public'],
include: [{
model: User,
as: 'specialUsers',
}],
where: {
$or : {
'$users.name$": 'Neill',
public: true
}
}
});
Should work if you are on a fairly recent version. Note that I moved the where out of the include