Hi smart people, i have problem with (many to many) assocation with sequelize orm - node.js

i have problem with (many to many) assocation with sequelize orm
In my case i have 3 tables
products,
categories,
products_categories
and here are assocation in nodeJS
Product.belongsToMany(Categories, {
through: {
model: ProductsCategories,
as: 'products_categories',
},
foreignKey: "category_id"
})
Categories.belongsToMany(Product, {
through: {
model: ProductsCategories,
as: 'products_categories',
},
foreignKey: "product_id"
})
when i'm trying to fetch products with categories
sequelize not gives me back categories of the product
here are example
const products = await Product.findAll({
include:{
model:Categories,
nested:true,
through:{
model: ProductsCategories,
as: 'products_categories',
}
}
});
please help me understand where are my mistak ))

Please correct your model definitions as:
Product.belongsToMany(Categories, {
through: ProductsCategories,
as: 'products_categories',
foreignKey: "category_id"
})
Categories.belongsToMany(Product, {
through: ProductsCategories,
as: 'products_categories',
foreignKey: "product_id"
})
and findAll:
const products = await Product.findAll({
include:{
model:Categories,
as: 'products_categories'
}
});

Related

Sequelize unable to model this relationship. X is not associated to Y

I have an Orders and Transactions table.
The id in Orders is to be used in the sellOrderId and buyOrderId columns
To model this in my Orders table I have
static associate({ Transactions }) {
Orders.hasMany(Transactions, { foreignKey: 'buyOrderId', sourceKey: 'id', as: 'buyTransactions' });
Orders.hasMany(Transactions, { foreignKey: 'sellOrderId', sourceKey: 'id', as: 'sellTransactions' });
}
In my Transactions model I have
static associate({ Orders }) {
Transactions.belongsTo(Orders, { foreignKey: 'id', targetKey: 'sellOrderId' });
Transactions.belongsTo(Orders, { foreignKey: 'id', targetKey: 'buyOrderId' });
}
I am attempting to get all Orders along with their associated transactions
I have tried many different queries but they all error out with the same error
EagerLoadingError [SequelizeEagerLoadingError]: Transaction is not associated to Orders!
Currently I have
const orders = await Order.findAll({
include: [
{
model: Transaction,
as: 'buyTransactions'
},
{
model: Transaction,
as: 'sellTransactions'
}
]
});
Regardless of if I have one or both same error, I can see in the database that the relationship exists, Im not sure why sequelize is not honoring this.

Sequelize one to Many insertion is not working?

This is my code :
const add_ticket = await db.Ticket.create({
userId,
travels: ticket.travels,
TicketInventory: {
fare: "Fare",
passenger: "passenger",
seatName: "seatName",
serviceTax: "serviceTax",
}
},
{
include: {
model: db.TicketInventory,
}})
I need to add "TicketInventory" details under "TicketInventory" table ! But it isnt adding - but rest of the details are been added to "ticket" table !
Association : Ticket HasMany TicketInventory and TicketInventory BelongsTo Ticket !
My assocaition code:
/// For Ticket Model
static associate(models) {
Ticket.hasMany(models.TicketInventory, {
foreignKey: 'ticketId',
onDelete: 'CASCADE' ,
as: 'vegetables'
});
}
};
/// For TicketInventory Model
static associate(models) {
TicketInventory.belongsTo(models.Ticket, {
foreignKey: 'ticketId',
});
}
Please help to resolve
This kind of thing...
const add_ticket = await db.Ticket.create({
userId,
travels: ticket.travels,
vegetables: [{
fare: "Fare",
passenger: "passenger",
seatName: "seatName",
serviceTax: "serviceTax",
}]
},
{
include: [{
model: db.TicketInventory,
as: "vegetables"
}]
})

Associations HasMany works but HasOne does not

I have two models defined in GraphQL Cars and Brands (their association is cars.brand_id = brands.id).
The schema only works when I define:
Cars.hasMany(models.brands, {
sourceKey: 'brand_id',
foreignKey: 'id'
})
Whereas it doesn't work if I define it in the following way:
Cars.hasOne(models.brands, {
sourceKey: 'brand_id',
foreignKey: 'id'
}),
Here I share a bit more of the schema (I am using makeExecutableSchema to split the files definitions):
Associations:
CarBrands.js
CarBrands.associate = models => {
CarBrands.hasOne(models.cars, {
foreignKey: 'brand_id',
});
}
Cars.js
Cars.associate = models => {
Cars.belongsTo(models.brands),
Cars.hasMany(models.car_images, {
foreignKey: {
name: 'car_id',
allowNull: false
},
onDelete: "cascade"
});
};
Car Model:
export const typeDef = `
type Cars {
user_id: Int!,
title: String!,
brands: [CarBrands!],
car_images: [CarImages],
}
`;
The SQL is well-formed, and car_images returns the data correctly whereas brands does not. Any idea why is that?
Any hint will be forever appreciated.
Thanks
You can find the document one-to-one-relationships at there: https://sequelize.org/master/manual/assocs.html#one-to-one-relationships
.In the document introduces 4 options to define one-to-one.
Try it:
Brands.hasOne(Cars, {
foreignKey: 'brand_id'
});
Cars.belongsTo(Brands);

Sequelize: Joining Many to Many tag table with another table in postgresql

I am trying to setup many to many relationship in Sequelize for my Postgres tables using a tag (lookup) table. I was successful in setting up the relationship.
Now my lookup table, has an additional field which is a foreign key to another table. I want the data for that table to be included in my result set. This is where I am having hard time figuring out the syntax.
My models:
Models.user = sequelize.define('user', { //attributes});
Models.school = sequelize.define('school', { //attributes });
Models.role = sequelize.define('role', { //attributes });
Models.userSchools = sequelize.define('user_school', {
user_school_id: { type: Sequelize.INTEGER, primaryKey: true }
});
Models.user.belongsToMany(Models.school, { through: Models.userSchools, foreignKey: 'user_id', otherKey: 'school_id' });
Models.school.belongsToMany(Models.user, { through: Models.userSchools, foreignKey: 'school_id', otherKey: 'user_id' });
Models.userSchools.belongsTo(Models.role, { foreignKey: 'role_id' });
Working query: This query gives me all the users and their schools.
Models.user.findAll({
where: {
//condition
},
include: [Models.school]
})
Now I want to include the role for each schools. None of the below queries are working.
Models.user.findAll({
where: {
//conditions
},
include: [Models.schools, Models.role]
})
Above query is throwing an error saying role is not associated to user, which is expected.
Models.user.findAll({
where: {
//conditions
},
include: [Models.schools, {model: Models.userSchools, include: Models.role}]
})
This query is also throwing an error:
"userSchools is not associated to user".
Can any one help with syntax to how I can get the role information from the userSchools model?
Edit:
I have add a "through" condition which gets me the role_id but not the related role data.
Models.user.findAll({
where: {
//conditions
},
include: [{
model: Models.school,
as: 'schools',
through: {
attributes: ['role_id']
}
}]
})

get associations with belongsToMany in sequelize.js

I have a many-to-many relation between User and Device model, through a UserDevice join table:
device.belongsToMany(user, {
through: {
model: userDevice
},
foreignKey: "deviceId",
as: "customers"
});
user.belongsToMany(device, {
through: {
model: userDevice
},
foreignKey: "customerId",
as: "devices"
});
setCustomers: Sequelize.BelongsToManySetAssociationsMixin<UserInstance, string, UserDeviceAttribute>;
getCustomers: Sequelize.BelongsToManyGetAssociationsMixin<UserInstance>;
I can find devices and populate customers correctly with:
this.db.models.Device.findAll({
include: [{
model: User,
as: "customers"
}]
I can't figure out how I can populate customers in other scenarios, i.e. when I'm setting customers manually. Right now I'm trying something like:
return device.setCustomers(customers)
.then(() => {
return device.getCustomers();
})
.then((users) => {
device.setAttributes("customers", users);
return device;
});
but it's not working, setAttributes doesn't set customers field.
The answer is in the question. I found the bug today when encountered same issue.
https://github.com/sequelize/sequelize/blob/master/lib/model.js#L3483
setAttributes seems to be a reserved method for sequelize.

Resources