'how to create association instance from source instance with sequelize
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: '[email protected]',
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: '[email protected]',
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',
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
