Accessing belongsToMany associates inside of instance

烈酒焚心 提交于 2019-12-24 18:56:21

问题


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.

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'});
      }
    }

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.


回答1:


classMethods and instanceMethods are removed

Breaking Changes

  const Model = sequelize.define('Model', {
    ...
  });

 // Class Method
 Model.associate = function (models) {
   ...associate the models
 };

 // Instance Method
 Model.prototype.someMethod = function () {..}


来源:https://stackoverflow.com/questions/45395844/accessing-belongstomany-associates-inside-of-instance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!