问题
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