I have 4 models: User, Skill, SkillToLearn, and SkillToTeach. The SkillToLearn and SkillToTeach contain two columns userId and skillId to keep track of a skill (given by skillId) that a user (given by userId) wants to learn or teach.
My goal is to use Sequelize's include statement such that I can return all users' data, including a list of skills they are learning and a list of skills they are teaching. I want a response similar to the following:
[
{
"id": 1,
"username": "janedoe",
"skillsLearning": [
{
"skillId": 1,
"name": "arts"
}
],
"skillsTeaching": [
{
"skillId": 2,
"name": "cooking"
}
]
}
]
However, instead, I'm getting the following response:
[
{
"id": 1,
"username": "janedoe",
"skillsLearning": [
{
"skillId": 1,
"Skill": {
"name": "arts"
}
}
],
"skillsTeaching": [
{
"skillId": 2,
"Skill": {
"name": "cooking"
}
}
]
}
]
I have tried to include Skill instead of SkillToLearn and SkillToTeach but I got an error saying that Skill is not associated to User. I am uncertain if my schemas and associations are incorrect.
User.js
const User = sequelize.define("User", {
username: {
type: DataTypes.STRING,
allowNull: false,
unique: true
},
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
validate: {
isEmail: true
}
},
password: {
type: DataTypes.STRING,
allowNull: false
},
description: {
type: DataTypes.TEXT
}
}, {
freezeTableName: true
});
User.associate = function (models) {
User.hasMany(models.SkillToLearn, {
as: "skillsLearning",
onDelete: "cascade",
foreignKey: "userId",
sourceKey: "id"
});
User.hasMany(models.SkillToTeach, {
as: "skillsTeaching",
onDelete: "cascade",
foreignKey: "userId",
sourceKey: "id"
});
};
Skill.js
const Skill = sequelize.define("Skill", {
name: {
type: DataTypes.STRING,
allowNull: false,
unique: true
}
}, {
freezeTableName: true
});
Skill.associate = function (models) {
Skill.hasMany(models.SkillToLearn, {
as: "usersLearning",
onDelete: "cascade",
foreignKey: "skillId",
sourceKey: "id"
});
Skill.hasMany(models.SkillToTeach, {
as: "usersTeaching",
onDelete: "cascade",
foreignKey: "skillId",
sourceKey: "id"
});
};
SkillToLearn.js
const SkillToLearn = sequelize.define("SkillToLearn", {
userId: {
type: DataTypes.INTEGER,
allowNull: false,
primaryKey: true
},
skillId: {
type: DataTypes.INTEGER,
allowNull: false,
primaryKey: true
}
}, {
freezeTableName: true
});
SkillToLearn.associate = function (models) {
SkillToLearn.belongsTo(models.User, {
foreignKey: "userId",
targetKey: "id"
});
SkillToLearn.belongsTo(models.Skill, {
foreignKey: "skillId",
targetKey: "id"
});
};
SkillToTeach.js
const SkillToTeach = sequelize.define("SkillToTeach", {
userId: {
type: DataTypes.INTEGER,
allowNull: false,
primaryKey: true
},
skillId: {
type: DataTypes.INTEGER,
allowNull: false,
primaryKey: true
}
}, {
freezeTableName: true
});
SkillToTeach.associate = function (models) {
SkillToTeach.belongsTo(models.User, {
foreignKey: "userId",
targetKey: "id"
});
SkillToTeach.belongsTo(models.Skill, {
foreignKey: "skillId",
targetKey: "id"
});
};
dataRoutes.js
db.User
.findAll({
attributes: ["id", "username"],
include: [
{
model: db.SkillToLearn,
as: "skillsLearning",
attributes: ["skillId"],
include: [
{
model: db.Skill,
attributes: ["name"]
}
]
},
{
model: db.SkillToTeach,
as: "skillsTeaching",
attributes: ["skillId"],
include: [
{
model: db.Skill,
attributes: ["name"]
}
]
}
]
})
.then(results => res.json(results));
});
Is there a way for me to get the skill's name without having it in an object? Should I just do multiple queries and construct the response using my own object literal? Thank you!
Related
I want to add in my sequelize query model, but i don't know how to do this correctly.
I have two tables: Regions and Countries. There is a relation between them called belongsToMany that is going through the table region_countries, there i have foreign keys region_id and country_id. For Region and Countries i have table with translation, for example: table translate_trgions has region and language_code name (en, fr, ru, etc.). And i am getting list of regions with countries with their translations.
My Region model
class Region extends Model {}
Region.init(
{
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
},
},
{ sequelize, timestamps: false, tableName: 'regions', modelName: 'Region' }
);
class RegionTranslate extends Model {}
RegionTranslate.init(
{
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
},
name: {
type: DataTypes.STRING,
allowNull: true,
},
region_id: {
type: DataTypes.INTEGER.UNSIGNED,
references: {
model: Region,
key: 'id',
},
},
language_code: {
type: DataTypes.INTEGER.UNSIGNED,
references: {
model: Language,
key: 'code',
},
},
},
{
sequelize,
timestamps: false,
tableName: 'regions_description',
modelName: 'RegionTranslate',
}
);
class RegionsCountries extends Model {}
RegionsCountries.init(
{
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
},
region_id: {
type: DataTypes.INTEGER.UNSIGNED,
references: {
model: Region,
key: 'id',
},
},
country_id: {
type: DataTypes.INTEGER.UNSIGNED,
references: {
model: Country,
key: 'id',
},
},
},
{
sequelize,
timestamps: false,
tableName: 'region_countries',
modelName: 'RegionsCountries',
}
);
Region.hasMany(RegionTranslate, {
foreignKey: 'region_id',
as: 'translate_regions',
});
RegionTranslate.belongsTo(Region, { foreignKey: 'region_id' });
Region.belongsToMany(Country, {
through: RegionsCountries,
foreignKey: 'region_id',
});
Country.belongsToMany(Region, {
through: RegionsCountries,
foreignKey: 'country_id',
});
Region.belongsToMany(CountryTranslate, {
through: RegionsCountries,
as: 'translate_countries',
foreignKey: 'country_id',
otherKey: 'id',
});
My Country Model
class Country extends Model {}
Country.init(
{
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
},
code: {
type: DataTypes.STRING,
allowNull: false,
},
unicode: {
type: DataTypes.INTEGER,
allowNull: false,
},
},
{ sequelize, timestamps: false, tableName: 'countries', modelName: 'Country' }
);
class CountryTranslate extends Model {}
CountryTranslate.init(
{
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
},
language_code: {
type: DataTypes.INTEGER,
allowNull: false,
references: {
model: Language,
key: 'code',
},
},
country_id: {
type: DataTypes.INTEGER,
allowNull: false,
references: {
model: Country,
key: 'id',
},
},
name: {
type: DataTypes.BOOLEAN,
allowNull: true,
},
description: {
type: DataTypes.BOOLEAN,
allowNull: true,
},
},
{
sequelize,
timestamps: false,
tableName: 'countries_description',
modelName: 'CountryTranslate',
}
);
Country.hasMany(CountryTranslate, {
foreignKey: 'country_id',
as: 'translate_countries',
});
CountryTranslate.belongsTo(Country, { foreignKey: 'country_id' });
Country.belongsToMany(Region, {
through: RegionsCountries,
foreignKey: 'country_id',
});
My query in RegionController
const regions = await Region.findAll({
attributes: {
include: [[Sequelize.literal('translate_regions.name'), 'name']],
},
include: [
{
model: Country,
attributes: {
include: [[Sequelize.literal('translate_countries.name'), 'name']],
},
through: {
attributes: [],
},
},
{
model: RegionTranslate,
as: 'translate_regions',
where: { language_code: language },
attributes: [],
},
{
model: CountryTranslate,
as: 'translate_countries',
},
],
});
The output i'm getting
"regions": [
{
"id": 4,
"name": "Europe",
"Countries": [
{
"id": 3,
"code": "dza",
"unicode": "12",
"name": "Ангола"
}
],
"translate_countries": [
{
"id": 10,
"language_code": "ru",
"country_id": 5,
"name": "Ангола",
"description": null,
"RegionsCountries": {
"id": 10,
"region_id": 4,
"country_id": 4
}
}
]
}
]
The output that i want
"regions": [
{
"id": 4,
"name": "Europe",
"Countries": [
{
"id": 4,
"code": "and",
"unicode": "20",
"name": "Andorra"
}
]
}
]
When setting up your Model associations for many-to-many through a relational table, you need to specify the columns in the relational table that is the foreign key for your source table primary key, as well as the column that is the "other" foreign key for the related table primary key. It's helpful to specify an as property as well to identify the relationship.
This is an example, check other relationships as well.
// use otherKey to indicate the relationship
// country.id -> country_id, region_id -> region.id
Country.belongsToMany(Region, {
as: 'regions',
through: RegionsCountries,
foreignKey: 'country_id',
otherKey: 'region_id'
});
When you query for related records we can no specify the through and as property on the query.
Country.findByPk(countryId, {
include: [{
model: Region,
through: RegionsCountries,
as: 'regions',
}],
});
I'm working in Node JS and Sequelize/MySQL. I have two tables Agent and Neighborhood as well as a join table AgentNeighborhood. I'd like, when querying these tables to obtain the join table key.
AgentNeighborhood
const AgentNeighborhood = sequelize.define('agentneighborhood', {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
allowNull: false
},
agent_id: {
type: DataTypes.INTEGER,
required: true,
references: {
model: 'Agent',
key: 'id'
},
allowNull: false
},
neighborhood_id: {
type: DataTypes.INTEGER,
required: true,
references: {
model: 'Neighborhood',
key: 'id'
},
allowNull: false
},
},
{
freezeTableName: true,
underscore: true
})
Neighborhood
const Neighborhood = sequelize.define('neighborhood', {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
allowNull: false,
},
...
...
},
{
freezeTableName: true,
})
Neighborhood.associate = (models) => {
Neighborhood.belongsToMany(models.agent, { through: 'agentneighborhood', foreignKey: 'neighborhood_id' })
}
Agent
const Agent = sequelize.define('agent', {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
allowNull: false
},
....
},
{
freezeTableName: true,
})
Agent.associate = (models) => {
Agent.belongsToMany(models.neighborhood, { through: 'agentneighborhood', foreignKey: 'agent_id' })
}
How can I query the keys so that my result will be as follows ?
{
id // the primary key for the AgentNeighborhood table
agent_id
agent {
id // should be same as agent_id
...
}
neighborhood_id
neighborhood {
id // should be same as neighborhood_id
...
}
}
I tried the following but get an error that neighborhood is not associated to agentneighborhood.
const agentneighborhoods = await models.agentneighborhood.findAll({where: {agent_id: 1}, include: [
{model: models.neighborhood},
{model: models.agent},
]})
return agentneighborhoods
You need to get list of neighbors associated with that agent_id.
const agentneighborhoods= await models.neighbors.findAll({
where: { "$agentneighborhood.agent_id$": agent_id },
include: [
{
as: "agentneighborhood",
model: models.agentneighborhood,
required: true
}
]
});
return agentneighborhoods
I am trying to build the models for a n:m association in Node JS using Sequelize.
The image who follows shows what I am trying to map in the backend:
Using the official documentation, the models that I have defined are the following:
let Dashboards = sequelize.define('Dashboards', {
name: DataType.STRING(30),
category: DataType.TINYINT(2)
}, {
freezeTableName: true,
timestamps: false,
tableName: 'dashboards'
});
Dashboards.associate = function (models) {
Dashboards.belongsToMany(models.Charts, {
through: {
unique: false,
model: models.DashboardCharts
},
foreignKey: 'dashboardId'
});
};
let Charts = sequelize.define('Charts', {
type: DataType.INTEGER(5),
title: DataType.STRING(30),
}, {
freezeTableName: true,
timestamps: false,
tableName: 'charts'
});
Charts.associate = function (models) {
Charts.belongsToMany(models.Dashboards, {
through: {
unique: false,
model: models.DashboardCharts,
},
foreignKey: 'chartId'
});
};
let DashboardCharts = sequelize.define('DashboardCharts', {
title: {
type: DataType.STRING(30)
},
color: {
type: DataType.STRING(7)
}
}, {
freezeTableName: true,
timestamps: false,
tableName: 'dashboard_charts'
});
Now, if using DashboardCharts I try to join the table with Dashboards in this way:
DashboardCharts.findAll({
include: [
{
model: Dashboard,
required: true,
}
]
})
I got this error: SequelizeEagerLoadingError: Dashboards is not associated to DashboardCharts!
What am I doing wrong? Thanks to anyone who could help me!
I found the solution: I was wrong doing the association. With the current configuration, I could only ask for Dashboard's charts or vice versa. The right solution is to set belongsTo from the join table, as it follows:
let Dashboards = sequelize.define('Dashboards', {
name: DataType.STRING(30),
category: DataType.TINYINT(2)
}, {
freezeTableName: true,
timestamps: false,
tableName: 'dashboards'
});
let Charts = sequelize.define('Charts', {
type: DataType.INTEGER(5),
title: DataType.STRING(30),
}, {
freezeTableName: true,
timestamps: false,
tableName: 'charts'
});
let DashboardCharts = sequelize.define('DashboardCharts', {
dashboard_id: {
type: DataType.INTEGER(5),
primaryKey: true
},
chart_id: {
type: DataType.INTEGER(5),
primaryKey: true
},
title: {
type: DataType.STRING(30)
},
color: {
type: DataType.STRING(7)
}
}, {
freezeTableName: true,
timestamps: false,
tableName: 'dashboard_charts'
});
DashboardCharts.associate = function (models) {
DashboardCharts.belongsTo(models.Dashboards, {
foreignKey: 'dashboard_id',
sourceKey: models.Dashboards.id
});
DashboardCharts.belongsTo(models.Charts, {
foreignKey: 'chart_id',
sourceKey: models.Charts.id
});
};
I've two models, User and Category
User model:
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define('User', {
id: {
type: DataTypes.BIGINT(19),
allowNull: false,
primaryKey: true,
autoIncrement: true
},
firstname: {
type: DataTypes.STRING(150),
allowNull: false
},
lastname: {
type: DataTypes.STRING(150),
allowNull: false
},
email: {
type: DataTypes.STRING(255),
allowNull: false,
unique: true
},
password: {
type: DataTypes.STRING(255),
allowNull: false
}
}, {
tableName: 'users',
timestamps: true,
createdAt: 'created_at',
updatedAt: 'updated_at',
defaultScope: {
attributes: {
exclude: ['password']
}
},
scopes: {
withPassword: {
attributes: {}
}
}
})
User.prototype.toJSON = function () {
let values = Object.assign({}, this.get())
delete values.password
return values
}
return User
}
Category model:
module.exports = (sequelize, DataTypes) => {
const Category = sequelize.define('Category', {
id: {
type: DataTypes.BIGINT(19),
allowNull: false,
primaryKey: true,
autoIncrement: true
},
name: {
type: DataTypes.STRING(150),
allowNull: false
},
created_by: {
type: DataTypes.BIGINT(19),
allowNull: false,
references: {
model: 'users',
key: 'id'
}
}
}, {
tableName: 'categories',
timestamps: true,
createdAt: 'created_at',
updatedAt: 'updated_at'
})
Category.associate = (models) => {
Category.belongsTo(models.User, {
foreignKey: 'created_by'
})
}
return Category
}
My query to find the category:
const category = await Category.findOne({
include: [{
model: User,
required: true,
attributes: ['id', 'firstname', 'lastname', 'email']
}],
where: {
id: req.params.id
},
limit: 1
})
When I execute the query, the response I expected was,
{
"id": 1,
"name": "License",
"created_by": {
"id": 1,
"firstname": "Magesh",
"lastname": "Kumaar",
"email": "mk#test.com"
},
"created_at": "2018-09-03T07:41:29.000Z",
"updated_at": "2018-09-03T07:41:29.000Z"
}
But the response I obtained was,
{
"id": 1,
"name": "License",
"created_by": 1, // I expected the user information here
"created_at": "2018-09-03T07:41:29.000Z",
"updated_at": "2018-09-03T07:41:29.000Z",
"User": {
"id": 1,
"firstname": "Magesh",
"lastname": "Kumaar",
"email": "mk#test.com"
}
}
The user information is available at both created_by as Id and another User property that contains other information
I tried the as option, but it didn't seem to work. Is there any way to get the user information in the created_by key itself.
Need use aliases.
http://docs.sequelizejs.com/manual/tutorial/associations.html
Example:
index.js
require('dotenv').load();
const { User, Category } = require('./models');
const sequelize = require('./database');
(async () => {
await sequelize.sync({ force: true });
await Category.associate({ User });
await User.create({
firstname: 'firstname',
lastname: 'lastname',
email: 'email#email.email',
password: 'password',
});
await Category.create({
name: 'name',
created_by: '1',
});
const category = await Category.findOne({
attributes: ['id'],
include: {
model: User,
required: true,
as: 'created',
attributes: ['id', 'firstname', 'lastname', 'email']
},
where: {
id: 1,
},
});
console.log(category.toJSON());
})();
Category Model file:
module.exports = (sequelize, DataTypes) => {
const Category = sequelize.define('Category', {
id: {
type: DataTypes.BIGINT(19),
allowNull: false,
primaryKey: true,
autoIncrement: true
},
name: {
type: DataTypes.STRING(150),
allowNull: false
},
created_by: {
type: DataTypes.BIGINT(19),
allowNull: false,
references: {
model: 'users',
key: 'id'
}
}
}, {
tableName: 'categories',
timestamps: true,
createdAt: false,
updatedAt: false,
});
Category.associate = (models) => {
Category.belongsTo(models.User, {
foreignKey: 'created_by',
as: 'created',
})
};
return Category;
};
result:
{ id: 1,
created:
{ id: 1,
firstname: 'firstname',
lastname: 'lastname',
email: 'email#email.email' } }
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...