非映射属性 - Sequelize

Non mapped properties - Sequelize

支持的有:React、Redux 和 Sequelize。 基本上我希望能够在 Redux 存储更新时将对象标记为 dirty

function updateCar(carToUpdate, car) {
    switch(car[1]) {
        case "models":
            carToUpdate.models = car[3];
            carToUpdate.setDirty();
            break;
    }    
};

然后当有人点击保存按钮时,我只想更新那些脏标志设置为 true 的模型

var state = request.body;

state.forEach(function (car) {
    if (car && car.isDirty) {
        updateCar(car);
    }
}

现在我的车有以下型号:

module.exports = function (sequelize, DataTypes) {
  var Cars = sequelize.define('Cars',
    {
      name: DataTypes.STRING,
      type: DataTypes.INTEGER,
      models: DataTypes.INTEGER,
      //Next is NOT working, this does not make it non-mapped
      isDirty: {
        type: DataTypes.BOOLEAN,
        scope: false
      },
    },
    {
      classMethods: {
        associate: function (models) {
          // associations can be defined here
        }
      },
      instanceMethods: {
        setDirty: function() {
          this.isDirty = true;
        }
      }
    });
  return Cars;
};

有人对非映射字段或类似字段有经验吗?

终于找到了。

汽车型号应包含 VIRTUAL 属性:

module.exports = function (sequelize, DataTypes) {
  var Cars = sequelize.define('Cars',
    {
      name: DataTypes.STRING,
      type: DataTypes.INTEGER,
      models: DataTypes.INTEGER,
      isDirty: {
        type: DataTypes.VIRTUAL
      },
    },
    {
      classMethods: {
        associate: function (models) {
          // associations can be defined here
        }
      }
    });
  return Cars;
};

下一步应该在更新值时设置标志:

function updateCar(carToUpdate, car) {
    switch(car[1]) {
        case "models":
            carToUpdate.models = car[3];
            carToUpdate.isDirty = true;
            break;
    }    
};

然后保存方法可以检查isDirty标志 变量状态 = request.body;

state.forEach(function (car) {
    if (car && car.isDirty) {
        console.log(car.name +": "+ car.isDirty);
        updateCar(car);
    }
}, this);

最后但同样重要的是,我们将 isDirty 标志重置为 false,这样我们就不会一遍又一遍地更新相同的模型。

var save = function () {
    var state = carStore.getState();
    return $.ajax({
        url: "/Cars/update",
        data: JSON.stringify(state),
        method: "POST",
        contentType: "application/json"
    }).then(function() {
        carStore.dispatch({
            type: 'resetDirty',
            data: null
        });
    });
};

以及重置标志的调度方法:

function updateReducer(state, action) {
    switch (action.type) {
        case 'load':
            return action.data;
        case 'update':
            return updateCars(action.carChanges, state);
        case 'resetDirty':
            return resetDirtyFlags(state);
        default:
            return action.data;
    }

}

function resetDirtyFlags(state) {
    var newState = $.extend(true, [], state);
    if(state) {
        newState.forEach(function(car) {
            car.isDirty = false;
        }, this);
        return newState;
    }
    return newState;
}