gpt4 book ai didi

node.js - Sequelize 关联 :Unhandled rejection TypeError: order. addItems 不是函数

转载 作者:行者123 更新时间:2023-12-03 22:36:24 24 4
gpt4 key购买 nike

关联定义为:

Orders.belongsToMany(Items, { through: OrderItem });
Items.belongsToMany(Orders, { through: OrderItem });

我正在努力
 Orders.create(orderDetails).then(order => {
orderDetails.items.forEach(item => {
Items.findByPk(item.code).then(item => {
order.addItem(item)
})
});
})

为什么这给我的错误是
Unhandled rejection TypeError: order.addItem is not a function

最佳答案

它应该工作。我正在使用 "sequelize": "^5.21.3" 。此外,您的代码还有另一个问题。您创建了一个订单,但 sequelize 不会在 items 对象中创建 orderDetails。您需要使用关联创建它们。您应该使用 Orders.create(orderDetails, { include: [Items] }) 创建项目。您可以查看此 docs 以了解详细信息。

让我们回到你的问题,order.addItem 应该可以工作。这是完成的工作示例:
index.ts :

import { Model, BelongsToManyAddAssociationMixin, DataTypes } from 'sequelize';
import { sequelize } from '../../db';

class Orders extends Model {
public id!: number;
public addItem!: BelongsToManyAddAssociationMixin<Items, number>;
}
Orders.init({}, { sequelize, modelName: 'order' });

class Items extends Model {
public code!: number;
public name!: string;
}
Items.init(
{
code: {
type: DataTypes.INTEGER,
primaryKey: true,
allowNull: false,
},
name: DataTypes.STRING,
},
{ sequelize, modelName: 'item' },
);

class OrderItem extends Model {
public orderId!: number;
public itemCode!: number;
}
OrderItem.init({}, { sequelize, modelName: 'orderItem' });

Orders.belongsToMany(Items, { through: OrderItem });
Items.belongsToMany(Orders, { through: OrderItem });

export { sequelize, Orders, Items, OrderItem };
index.test.ts :

import { sequelize, Orders, Items } from './';

describe('59818484', () => {
beforeAll(async () => {
await sequelize.sync({ force: true });
});
afterAll(async () => {
await sequelize.close();
});
it('should pass', (done) => {
expect.assertions(3);
const orderDetails = {
items: [
{ code: 1, name: 'a' },
{ code: 2, name: 'b' },
],
};
let count = 0;
Orders.create(orderDetails).then(async (order: Orders) => {
const items = await Items.findAll();
expect(items).toHaveLength(0);
orderDetails.items.forEach((item) => {
Items.findByPk(item.code)
.then((item: Items) => {
expect(typeof order.addItem).toBe('function');
return order.addItem(item);
})
.finally(() => {
count++;
if (count === orderDetails.items.length) {
done();
}
});
});
});
});
});

集成测试结果:

 PASS  src/examples/stackoverflow/59818484/index.test.ts
59818484
✓ should pass (34ms)

Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 3.23s

源代码: https://github.com/mrdulin/node-sequelize-examples/tree/master/src/examples/stackoverflow/59818484

关于node.js - Sequelize 关联 :Unhandled rejection TypeError: order. addItems 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59818484/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com