问题描述
我正在使用 sequelize 将现有 Rails 应用程序转换为 nodejs 以连接到现有数据库(使用 ActiveRecord 创建).这是一个购物应用程序,所以我有一个 Product 类和一个 Cart 类,我想将它们关联在一起.在我现有的应用程序中,我使用第三个类 CartLineItem 将它们关联在一起.
I am in the process of converting an existing rails app to nodejs using sequelize to interface to the existing database (created using ActiveRecord). This is a shopping application, so I have a Product class and a Cart class that I want to associate together. In my existing application I use a third class, CartLineItem to associate them together.
在 Product 类中,我使用以下内容:
Inside of the Product class I use the following:
classMethods:
{
associate: function(models) {
Cart.belongsToMany(models.Product, { through: models.CartLineItem,
foreignKey: 'cart_id',
otherKey: 'product_id',
as: 'products'});
}
}
在产品内部,我做相反的事情.我似乎能够在购物车中添加和删除商品,但现在我想添加一个实例方法来返回总价,但我不知道如何访问 Cart 实例中的相关产品来合计价格.做到这一点的最佳方法是什么?我希望这样做足够频繁,以至于我不想每次需要时都在模型之外进行操作.谢谢.
And inside of the Product I do the reverse. I appear to be able to add and remove items to/from the cart, but now I'd like to add an instance methods to return the total price and I can't figure out how to access the associated products within the instance of Cart to total up the prices. What's the best way to do this? I expect to do this frequently enough that I don't want to do the operation outside of the model each time I need it. Thanks.
推荐答案
classMethods 和 instanceMethods 被移除
classMethods and instanceMethods are removed
const Model = sequelize.define('Model', {
...
});
// Class Method
Model.associate = function (models) {
...associate the models
};
// Instance Method
Model.prototype.someMethod = function () {..}
这篇关于访问实例内的belongsToMany 关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!