Краткий ответ, так как вы используете опцию псевдонима (as
). Это утверждение as: 'coupon_type'
, вам нужно использовать Coupon.getCoupon_type()
, чтобы получить ItemType
из Coupon
.
Длинный ответ, вот рабочий пример:
index.ts
:
import { sequelize } from '../../db';
import { Model, DataTypes } from 'sequelize';
class Coupon extends Model {}
Coupon.init(
{
coupon_id: {
unique: true,
type: DataTypes.BIGINT,
},
},
{ sequelize, modelName: 'Coupons' },
);
class ItemType extends Model {}
ItemType.init(
{
item_type_id: {
unique: true,
type: DataTypes.SMALLINT,
},
},
{ sequelize, modelName: 'ItemTypes' },
);
class CouponItemType extends Model {}
CouponItemType.init(
{
coupon_id: DataTypes.BIGINT,
item_type_id: DataTypes.SMALLINT,
created_by: DataTypes.STRING,
updated_by: DataTypes.STRING,
created_on: DataTypes.DATE,
updated_on: DataTypes.DATE,
},
{ sequelize, modelName: 'CouponItemType' },
);
Coupon.belongsToMany(ItemType, {
through: 'CouponItemType',
as: 'coupon_type',
foreignKey: 'coupon_id',
otherKey: 'item_type_id',
});
ItemType.belongsToMany(Coupon, {
through: 'CouponItemType',
as: 'coupon_item_types',
foreignKey: 'item_type_id',
otherKey: 'coupon_id',
});
(async function test() {
try {
await sequelize.sync({ force: true });
const couponDataRecords = [
{ coupon_id: 1, coupon_type: [{ item_type_id: 1 }, { item_type_id: 2 }] },
{ coupon_id: 2, coupon_type: [{ item_type_id: 4 }, { item_type_id: 3 }] },
];
await Coupon.bulkCreate(couponDataRecords, {
include: [
{
model: ItemType,
as: 'coupon_type',
},
],
});
const coupon = await Coupon.findOne({ where: { coupon_id: 1 } });
const validForType = await coupon.getCoupon_type({
where: {
item_type_id: 1,
},
attributes: ['id'],
raw: true,
});
console.log('validForType: ', validForType);
} catch (error) {
console.log(error);
} finally {
await sequelize.close();
}
})();
Результат выполнения кода выше:
validForType: [ { id: 1,
'CouponItemType.coupon_id': 1,
'CouponItemType.item_type_id': 1,
'CouponItemType.created_by': null,
'CouponItemType.updated_by': null,
'CouponItemType.created_on': null,
'CouponItemType.updated_on': null } ]
Проверка записей данных в базе данных:
node-sequelize-examples=# select * from "Coupons";
id | coupon_id
----+-----------
1 | 1
2 | 2
(2 rows)
node-sequelize-examples=# select * from "ItemTypes";
id | item_type_id
----+--------------
1 | 1
2 | 2
3 | 4
4 | 3
(4 rows)
node-sequelize-examples=# select * from "CouponItemType";
coupon_id | item_type_id | created_by | updated_by | created_on | updated_on
-----------+--------------+------------+------------+------------+------------
1 | 1 | | | |
1 | 2 | | | |
2 | 3 | | | |
2 | 4 | | | |
(4 rows)
db.ts
:
const sequelize = new Sequelize({
dialect: 'postgres',
host: envVars.POSTGRES_HOST,
username: envVars.POSTGRES_USER,
password: envVars.POSTGRES_PASSWORD,
database: envVars.POSTGRES_DB,
port: Number.parseInt(envVars.POSTGRES_PORT, 10),
define: {
freezeTableName: true,
timestamps: false,
},
});
Версия Sequelize: "sequelize": "^5.21.3"
Исходный код: https://github.com/mrdulin/node-sequelize-examples/tree/master/src/examples/stackoverflow/60449016