I have 1:n association User -> Cart, what I want is, I find User by Id then create Cart by that instance and then fill the product_id manually
I'm using sequelize
I have tried get,set,create from this association and none of them worked, it gave me this error
TypeError: user.createCart is not a function
at /home/horus/beginner-html-site-scripted/server/controllers/Cart.controller.ts:21:26
and this is my CartController:
const { product_id } = req.params;
const product = await ProductModel.findByPk(product_id);
if (!product) {
return res.status(401).json({ message: 'product not found' });
}
//#ts-ignore
const userData = req.user;
const user = await UserModel.findByPk(userData.user_id);
if (!user) return res.status(401).json({ message: 'user not found' });
const cart = await user.createCart();
res.status(200).json({ message: '', cartData: user.getCart() });
those are my Models:
Cart Class
export default class Cart
extends Model<InferAttributes<Cart>, InferCreationAttributes<Cart>>
implements CartInterface {
declare cart_id: CreationOptional<string>;
declare quantity: CreationOptional<number>;
declare user_id: string;
}
Cart.init(
{
cart_id: { type: UUID, defaultValue: UUIDV4, primaryKey: true },
quantity: { type: INTEGER, defaultValue: 1 },
user_id: {
type: UUID,
references: {
model: 'Users',
key: 'user_id',
},
},
},
{ sequelize: db, tableName: 'Carts' }
);
User Class
export default class User
extends Model<InferAttributes<User>, InferCreationAttributes<User>>
implements UserInterface {
declare user_id: CreationOptional<string>;
declare firstName: string;
declare lastName: string;
declare email: string;
declare password: string;
declare avatar: string;
declare verificationCode: CreationOptional<string>;
declare passwordResetCode: CreationOptional<string>;
declare verified: CreationOptional<boolean>;
declare isAdmin: CreationOptional<boolean>;
// timestamps!
// createdAt can be undefined during creation
declare createdAt: CreationOptional<Date>;
// updatedAt can be undefined during creation
declare updatedAt: CreationOptional<Date>;
declare createSession: HasManyCreateAssociationMixin<Session, 'user_id'>;
declare createCart: HasOneCreateAssociationMixin<CartModel>;
declare setCart: HasOneSetAssociationMixin<CartModel, 'cart_id'>;
declare getCart: HasOneGetAssociationMixin<CartModel>;
}
User.init(
{
user_id: {
primaryKey: true,
allowNull: false,
type: UUID,
defaultValue: UUIDV4,
},
firstName: { type: new STRING(128), allowNull: false },
lastName: { type: new STRING(128), allowNull: false },
email: { type: new STRING(128), allowNull: false, unique: true },
password: {
type: new STRING(128),
allowNull: false,
},
avatar: { type: new STRING(128), defaultValue: '' },
verificationCode: { type: UUID, allowNull: false, defaultValue: UUIDV4 },
passwordResetCode: { type: UUID, allowNull: false, defaultValue: '' },
verified: { type: BOOLEAN, defaultValue: false, allowNull: false },
isAdmin: { type: BOOLEAN, defaultValue: false, allowNull: false },
createdAt: DATE,
updatedAt: DATE,
},
{
sequelize: db,
tableName: 'Users',
}
);
user Data
User {
dataValues: {
user_id: '20b42b70-f777-420b-b15b-cbf3732c1a9b',
firstName: 'leo',
lastName: 'qal',
email: 't#gmail.com',
password: '$2.',
avatar: '',
verificationCode: '',
passwordResetCode: '',
verified: true,
isAdmin: true,
createdAt: 2022-02-17T16:49:40.000Z,
updatedAt: 2022-02-17T16:49:40.000Z
},
_previousDataValues: {
user_id: '20b42b70-f777-420b-b15b-cbf3732c1a9b',
firstName: 'leo',
lastName: 'qal',
email: 't#gmail.com',
password: '$2.',
avatar: '',
verificationCode: '',
passwordResetCode: '',
verified: true,
isAdmin: true,
createdAt: 2022-02-17T16:49:40.000Z,
updatedAt: 2022-02-17T16:49:40.000Z
},
uniqno: 1,
_changed: Set(0) {},
_options: {
isNewRecord: false,
_schema: null,
_schemaDelimiter: '',
raw: true,
attributes: [
'user_id',
'firstName',
'lastName',
'email',
'password',
'avatar',
'verificationCode',
'passwordResetCode',
'verified',
'isAdmin',
'createdAt',
'updatedAt'
]
},
isNewRecord: false
}
Associations
UserModel.hasOne(CartModel, {
sourceKey: 'user_id',
foreignKey: 'user_id',
as: 'users',
});
CartModel.belongsTo(UserModel, {
foreignKey: 'cart_id',
as: 'carts',
});
//OneToMany Association
UserModel.hasMany(SessionModel, {
sourceKey: 'user_id',
foreignKey: 'user_id',
as: 'sessions', // this determines the name in `associations`!
});
CategoryModel.hasMany(ProductModel, {
sourceKey: 'category_id',
foreignKey: 'category_id',
as: 'products',
});
Related
I have a nodejs app using sequelize and postgres as a database, the architecture of the app is multitenant with separate schemas in the same database, the problem I present is that when including the permissions model in the user query, sequelize It doesn't take me the schema for the join table and therefore tries to query it in the default schema (public). these are my models:
Users:
export const USERS_TABLE = 'users';
#Table({
timestamps: false,
tableName: USERS_TABLE,
})
export class User extends Model {
#AfterCreate
static deletePassword(instance: User) {
instance.password = null;
}
#Column({
autoIncrement: false,
primaryKey: true,
type: DataType.STRING(36),
defaultValue: UUIDV4(),
field: 'user_id',
allowNull: false,
})
userId: string;
#Column({
type: DataType.STRING(20),
})
provider: string;
#Column({
type: DataType.STRING(50),
allowNull: false,
unique: true,
})
email: string;
#Column({
type: DataType.STRING(100),
field: 'customer_id',
unique: true,
})
customerId: string;
#Column({
type: DataType.STRING(50),
allowNull: false,
unique: true,
})
username: string;
#Column({
type: DataType.STRING(10),
unique: true,
})
phone: string;
#Column({
type: DataType.STRING(255),
field: 'recovery_token',
unique: true,
})
recoveryToken: string;
#Column({
type: DataType.STRING(10),
field: 'verify_code',
})
verifyCode: string;
#Column({
type: DataType.STRING(100),
})
password: string;
#Column({
type: DataType.TEXT,
})
devices: string;
#Column({
type: DataType.BOOLEAN,
defaultValue: false,
})
deleted: boolean;
#Column({
type: DataType.BOOLEAN,
defaultValue: false,
})
verified: boolean;
#Column({
type: DataType.INTEGER,
defaultValue: 1,
})
status: number;
#ForeignKey(() => Role)
#Column({
type: DataType.STRING(36),
field: 'role_id',
allowNull: false,
references: {
model: ROLES_TABLE,
key: 'id',
},
onUpdate: 'CASCADE',
onDelete: 'SET NULL',
})
roleId: string;
#ForeignKey(() => Profile)
#Column({
type: DataType.STRING,
field: 'profile_id',
allowNull: false,
references: {
model: PROFILES_TABLE,
key: 'id',
},
onUpdate: 'CASCADE',
onDelete: 'SET NULL',
})
profileId: string;
#ForeignKey(() => Subscription)
#Column({
type: DataType.STRING,
field: 'subscription_id',
references: {
model: SUBSCRIPTION_TABLE,
key: 'subscription_id',
},
onUpdate: 'CASCADE',
onDelete: 'SET NULL',
})
subscriptionId: string;
#Column({
allowNull: false,
type: DataType.DATE,
field: 'created_at',
defaultValue: new Date(),
})
createdAt: Date;
#Column({
allowNull: false,
type: DataType.DATE,
field: 'updated_at',
defaultValue: new Date(),
})
updatedAt: Date;
// Prueba tenantId
#Column({
type: DataType.STRING(36),
field: 'tenant_id',
references: {
model: TENANT_TABLE,
key: 'id',
},
onUpdate: 'CASCADE',
onDelete: 'SET NULL',
})
tenantId?: string;
#ForeignKey(() => Seat)
#Column({
type: DataType.STRING(36),
field: 'seat_id',
references: {
model: SEAT_TABLE,
key: 'seat_id',
},
onUpdate: 'CASCADE',
onDelete: 'SET NULL',
})
seatId: string;
// associations
#BelongsToMany(() => Permission, () => UserPermission)
Permissions: Permission[];
#BelongsTo(() => Subscription) Subscription: Subscription;
#BelongsTo(() => Profile) Profile: Profile;
#BelongsTo(() => Role) Role: Role;
#BelongsTo(() => Seat) Seat: Seat;
}
Permissions
export const PERMISSIONS_TABLE = 'permissions';
#Table({
timestamps: false,
tableName: PERMISSIONS_TABLE,
})
export class Permission extends Model {
#Column({
allowNull: false,
field: 'permission_id',
autoIncrement: false,
primaryKey: true,
type: DataType.STRING(36),
defaultValue: UUIDV4(),
})
permissionId: string;
#Column({
type: DataType.STRING(20),
allowNull: false,
})
name: string;
#Column({
type: DataType.STRING(150),
})
description: string;
#Column({
type: DataType.TEXT,
allowNull: false,
})
models: string;
#ForeignKey(() => Subscription)
#Column({
type: DataType.STRING,
allowNull: false,
field: 'subscription_id',
references: {
model: SUBSCRIPTION_TABLE,
key: 'subscription_id',
},
onUpdate: 'CASCADE',
onDelete: 'SET NULL',
})
subscriptionId: string;
#Column({
type: DataType.BOOLEAN,
allowNull: false,
defaultValue: true,
})
status: boolean;
#Column({
type: DataType.STRING(36),
field: 'tenant_id',
references: {
model: TENANT_TABLE,
key: 'id',
},
onUpdate: 'CASCADE',
onDelete: 'SET NULL',
})
tenantId?: string;
#Column({
allowNull: false,
type: DataType.DATE,
field: 'created_at',
defaultValue: new Date(),
})
createdAt: Date;
#Column({
allowNull: false,
type: DataType.DATE,
field: 'updated_at',
defaultValue: new Date(),
})
updatedAt: Date;
// Associations
#BelongsToMany(() => User, () => UserPermission) Users: User[];
}
Join Table
export const USERS_PERMISSIONS_TABLE = 'user_permissions';
#Table({
timestamps: false,
tableName: USERS_PERMISSIONS_TABLE,
})
export class UserPermission extends Model {
#ForeignKey(() => User)
#Column({
type: DataType.STRING,
field: 'user_id',
allowNull: false,
references: {
model: USERS_TABLE,
key: 'user_id',
},
onUpdate: 'CASCADE',
onDelete: 'SET NULL',
})
userId: string;
#ForeignKey(() => Permission)
#Column({
type: DataType.STRING,
field: 'permission_id',
allowNull: false,
references: {
model: PERMISSIONS_TABLE,
key: 'permission_id',
},
onUpdate: 'CASCADE',
onDelete: 'SET NULL',
})
permissionId: string;
}
I pass the necessary parameters to a base class that performs my query
users = await super.getAll(
tenantId,
[
Role.schema(schemaName),
Profile.schema(schemaName),
Subscription,
Permission.schema(schemaName),
],
body.page,
body.size,
{},
);
findAll method of Super Class
public async getAll(
tenantId: string,
includeModel?: object,
page?: string,
size?: string,
where?: Record<string, unknown>,
) {
try {
// free_id
let records: unknown;
const free = tenantId.split('_');
const tenantName: string = getTenantName(tenantId);
if (free[0] === 'free') {
where.tenantId = free[1];
}
if (!includeModel) {
const { limit, offset } = paginate(page, size);
records = await this.model.schema(tenantName).findAndCountAll({
where,
limit,
offset,
});
return new HttpResponse.getSuccessful(records);
}
const { limit, offset } = paginate(page, size);
records = await this.model.schema(tenantName).findAndCountAll({
where,
limit,
offset,
include: includeModel,
});
return new HttpResponse.getSuccessful(records);
} catch (e) {
throw boom.badRequest(e);
}
}
The generated query And The error:
sql: `SELECT count("User"."user_id") AS "count" FROM "free_trial"."users" AS "User" LEFT OUTER JOIN "free_trial"."roles" AS "Role" ON "User"."role_id" = "Role"."role_id" LEFT OUTER JOIN "free_trial"."profiles" AS "Profile" ON "User"."profile_id" = "Profile"."profile_id" LEFT OUTER JOIN "subscriptions" AS "Subscription" ON "User"."subscription_id" = "Subscription"."subscription_id" LEFT OUTER JOIN ( "user_permissions" AS "Permissions->UserPermission" INNER JOIN "free_trial"."permissions" AS "Permissions" ON "Permissions"."permission_id" = "Permissions->UserPermission"."permission_id") ON "User"."user_id" = "Permissions->UserPermission"."user_id" WHERE "User"."tenant_id" = '72a5afbe-dc66-4b54-a428-d7bed9a2cbd9';`,
parameters: {},
isBoom: true,
isServer: false,
data: null,
output: {
statusCode: 400,
payload: {
statusCode: 400,
error: 'Bad Request',
message: 'no existe la relación «user_permissions»'
},
headers: {}
}
}
As can be seen in the query, all the tables are preceded by the name of the schema in which they are found, but in the join table it refers to the public schema and therefore it cannot be found; I have already tried thousands of ways but nothing seems to work, any ideas are appreciated.
I have tried to pass the name of the schema to the join table, referring to it in the include but it does not give results, I also tried within permissions to include the join table to be able to pass the name of the schema.
I would like to find out what is the right way to add a many-to-many relation when seeding records with sequelize-cli. Now I understand that the easiest way to do this is to create another seeder file and manually set the values but is there a way to make some changes to my 2_user seeder file so that when a user is seeded with some value given for the role it automatically makes a record in the user_roles table. So basically same as the user.setRoles() one can use but in the seeder files. Any help is much appreciated.
Models
user.model.js
'use strict';
const { Model } = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class User extends Model {
static associate(models) {
User.belongsToMany(models.Role, {
through: 'user_roles',
foreignKey: 'user_id',
otherKey: 'role_id',
onDelete: 'CASCADE',
onUpdate: 'CASCADE',
});
User.hasMany(models.User_Role);
User.hasMany(models.Address, {
foreignKey: 'user_id',
onDelete: 'CASCADE',
onUpdate: 'CASCADE',
});
}
}
User.init(
{
user_id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
},
email: DataTypes.STRING,
password: DataTypes.STRING,
bio: DataTypes.STRING,
activity_status: DataTypes.BOOLEAN,
},
{
sequelize,
modelName: 'User',
}
);
return User;
};
role.model.js
'use strict';
const { Model } = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class User extends Model {
static associate(models) {
User.belongsToMany(models.Role, {
through: 'user_roles',
foreignKey: 'user_id',
otherKey: 'role_id',
onDelete: 'CASCADE',
onUpdate: 'CASCADE',
});
User.hasMany(models.User_Role);
User.hasMany(models.Address, {
foreignKey: 'user_id',
onDelete: 'CASCADE',
onUpdate: 'CASCADE',
});
}
}
User.init(
{
user_id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
},
email: DataTypes.STRING,
password: DataTypes.STRING,
bio: DataTypes.STRING,
activity_status: DataTypes.BOOLEAN,
},
{
sequelize,
modelName: 'User',
}
);
return User;
};
user_role.model
'use strict';
const { Model } = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class User_Role extends Model {
static associate(models) {
User_Role.belongsTo(models.User, {
foreignKey: 'user_id',
});
User_Role.belongsTo(models.Role, {
foreignKey: 'role_id',
});
}
}
User_Role.init(
{
user_role_id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
allowNull: false,
},
},
{
sequelize,
modelName: 'User_Role',
}
);
return User_Role;
};
Migrations
1-create-user
'use strict';
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.createTable('users', {
user_id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER,
},
email: {
type: Sequelize.STRING,
unique: true,
},
password: {
type: Sequelize.STRING,
},
bio: {
type: Sequelize.STRING,
},
activity_status: {
type: Sequelize.BOOLEAN,
},
createdAt: {
allowNull: false,
type: Sequelize.DATE,
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE,
},
});
},
async down(queryInterface, Sequelize) {
await queryInterface.dropTable('users');
},
};
3-create-role
'use strict';
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.createTable('roles', {
role_id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
unique: true,
type: Sequelize.INTEGER,
},
user_type: {
type: Sequelize.STRING,
},
createdAt: {
allowNull: false,
type: Sequelize.DATE,
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE,
},
});
},
async down(queryInterface, Sequelize) {
await queryInterface.dropTable('roles');
},
};
6-create-user_role
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.createTable('user_roles', {
user_role_id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER,
},
user_id: {
type: Sequelize.INTEGER,
references: { model: 'users', key: 'user_id' },
onDelete: 'CASCADE',
},
role_id: {
type: Sequelize.INTEGER,
references: { model: 'roles', key: 'role_id' },
onDelete: 'CASCADE',
},
createdAt: {
allowNull: false,
type: Sequelize.DATE,
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE,
},
});
},
async down(queryInterface, Sequelize) {
await queryInterface.dropTable('user_roles');
},
};
Seeders
1_role
'use strict';
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.bulkInsert(
'roles',
[
{
user_type: 'courier',
createdAt: new Date(),
updatedAt: new Date(),
},
{
user_type: 'receiver',
createdAt: new Date(),
updatedAt: new Date(),
},
{
user_type: 'donor',
createdAt: new Date(),
updatedAt: new Date(),
},
{
user_type: 'admin',
createdAt: new Date(),
updatedAt: new Date(),
},
],
{}
);
},
async down(queryInterface, Sequelize) {
await queryInterface.bulkDelete('Roles', null, {});
},
};
2_user
('use strict');
var bcrypt = require('bcryptjs');
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.bulkInsert(
'users',
[
{
email: 'courier#email.com',
password: bcrypt.hashSync('PassWord123#', 10),
bio: 'This is a courier type user!',
activity_status: true,
createdAt: new Date(),
updatedAt: new Date(),
role_id: 1,
},
{
email: 'donor#email.com',
password: bcrypt.hashSync('PassWord123#', 10),
bio: 'This is a donor type user!',
activity_status: true,
createdAt: new Date(),
updatedAt: new Date(),
},
{
email: 'receiver#email.com',
password: bcrypt.hashSync('PassWord123#', 10),
bio: 'This is a Receiver type user!',
activity_status: true,
createdAt: new Date(),
updatedAt: new Date(),
},
{
email: 'admin#email.com',
password: bcrypt.hashSync('PassWord123#', 10),
bio: 'This is a Admin type user!',
activity_status: true,
createdAt: new Date(),
updatedAt: new Date(),
},
],
{}
);
},
async down(queryInterface, Sequelize) {
await queryInterface.bulkDelete('Users', null, {});
},
};
Is it possible that sequelize automatically finds foreignKey IDs?
Or is it necessary to find out existing IDs manually before a new insert.
e.g. if I have a user table with mapping from user-id to username.
From an API request I only know the users name but in all tables I need the ID.
const Users = dbConn.define('Users', {
id: {
field: 'usersId',
type: DataTypes.NUMBER,
primaryKey: true,
},
userName: {
field: 'usersName',
type: DataTypes.NUMBER,
allowNull: false,
},
});
const ChartSettings = dbConn.define('ChartSettings', {
id: {
field: 'CS_ID',
type: DataTypes.NUMBER,
primaryKey: true,
},
userId: {
field: 'UserId',
type: DataTypes.NUMBER,
allowNull: false,
},
clientType: {
field: 'ClientType',
type: DataTypes.STRING,
allowNull: false,
},
cS_Name: {
field: 'CS_Name',
type: DataTypes.STRING,
allowNull: false,
},
settings: {
field: 'Settings',
type: 'VARBINARY(MAX)',
allowNull: false,
},
}, {
timestamps: false
});
// 1:M mapping
User.hasMany(ChartSettings, { foreignKey: 'userId' });
ChartSettings.belongsTo(User, { foreignKey: 'id' });
// actually I do it like this
const userId = await getUserIdByName('admin'); // e.g. this results in 154
const row = ChartSettings.build({
userId: 154,
clientType: 'some text',
cS_Name: 'some text',
settings: 0,
});
row.save();
// ... but I would like to insert a new entry without having the users-ID
const row = ChartSettings.build({
// userId: ?
userName: 'admin', // will be automatically mapped. possible?
clientType: 'some other txt',
cS_Name: 'some other txt',
settings: 0,
});
row.save();
I have a classical many-to-many relationship for users which own assets: assets can be transfered to other users during their life so a window time is recorded in the AssetUser "through table",
adding STARTDATE and ENDDATE attributes.
User Table
const User = sequelize.define('User', {
ID: {
type: DataTypes.INTEGER.UNSIGNED,
allowNull: false,
primaryKey: true
},
FIRSTNAME: {
type: DataTypes.STRING,
allowNull: false
},
LASTNAME: {
type: DataTypes.STRING,
allowNull: false
}},{ timestamps: false }});
Asset Table
const Asset = sequelize.define('Asset', {
ID: {
type: DataTypes.INTEGER.UNSIGNED,
allowNull: false,
primaryKey: true
},
DESCRIPTION: {
type: DataTypes.STRING,
allowNull: false
}},{ timestamps: false }});
AssetUser Join Table
const AssetUser = sequelize.define('AssetUser', {
id: {
type: DataTypes.INTEGER.UNSIGNED,
primaryKey: true,
autoIncrement: true,
allowNull: false
},
UserID: {
type: DataTypes.INTEGER.UNSIGNED,
references: {
model: User,
key: 'ID'
}
},
AssetID: {
type: DataTypes.INTEGER.UNSIGNED,
references: {
model: Asset,
key: 'ID'
}
},
STARTDATE: {
type: DataTypes.DATE,
defaultValue: DataTypes.NOW
},
ENDDATE: {
type: DataTypes.DATE,
allowNull: true,
defaultValue: null
}},{ timestamps: false });
The models are created here:
User.belongsToMany(Asset, { through: { model: AssetUser, unique: false }, uniqueKey: 'id' });
Asset.belongsToMany(User, { through: { model: AssetUser, unique: false }, uniqueKey: 'id' });
My problem is that I want to query and find all the results where one asset, owned by one user, during a restricted period. I am not able to query the join-table but only User and Assets tables.
How can I add a "where" condition for the AssetUser table inside my query? How should I insert a STARTDATE and/or ENDDATE condition below?
Asset.findAll({
where: {
DESCRIPTION: 'Personal computer'
},
include: {
model: User,
where: {
FIRSTNAME: 'Marcello'
}
}});
Thanks for your help.
I found the solution
Asset.findAll({ where: { DESCRIPTION: 'Personal computer' }, include: { model: User, through: { where: { FIRSTNAME: 'Marcello' } } }});
I have the following problem:
I defined my tables (product and collection) like this:
module.exports = (sequelize, type) => {
return sequelize.define('product', {
id: {
type: type.UUID,
primaryKey: true,
defaultValue: type.UUIDV4,
},
title: {
type: type.STRING,
allowNull: false,
},
description: {
type: type.TEXT,
allowNull: false,
},
width: {
type: type.FLOAT,
allowNull: false,
},
height: {
type: type.FLOAT,
allowNull: false,
},
weight: {
type: type.FLOAT,
allowNull: false,
},
length: {
type: type.FLOAT,
allowNull: false,
},
vendor: {
type: type.STRING,
allowNull: false,
},
status: {
type: type.ENUM,
values: ['inactive', 'active'],
defaultValue: 'active',
allowNull: false,
},
})
}
module.exports = (sequelize, type) => {
return sequelize.define('collection', {
id: {
type: type.UUID,
primaryKey: true,
defaultValue: type.UUIDV4,
},
name: {
type: type.STRING,
allowNull: false,
},
image: {
type: type.STRING,
allowNull: true,
},
createdAt: {
type: type.DATE,
allowNull: false,
},
updatedAt: {
type: type.DATE,
allowNull: false,
},
status: {
type: type.ENUM,
values: ['inactive', 'active'],
defaultValue: 'active',
allowNull: false,
},
})
}
Then, I need associated the tables (product and collection) with belongsToMany association and i did it like this:
const ProductModel = require('../api/product/model')
const CategoryModel = require('../api/category/model')
const Product = ProductModel(sequelize, Sequelize)
const Collection = CollectionModel(sequelize, Sequelize)
Product.belongsToMany(Collection, {
through: ProductCollection,
foreignKey: 'productId',
otherKey: 'collectionId',
unique: false,
})
Collection.belongsToMany(Product, {
through: ProductCollection,
foreignKey: 'collectionId',
otherKey: 'productId',
unique: false,
})
Now, i want to get all the products of a collection given by the id sent from the body of the request, i have little time working with sequelize and i don´t know how to do this kind of query.
Can you help me with that?
you can use something like this
let products = Collection.findAll({
where: {
id: collection.id,
},
attributes: ['id', 'name'],
include: [{
model: Product,
through: {
model: ProductCollection,
},
as: 'products',
attributes: ['id', 'title', 'description']
}],
});
return products
hope it helps