Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ssis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sails.js 如何根据Sails中的另一个模型属性验证模型属性?_Sails.js - Fatal编程技术网

Sails.js 如何根据Sails中的另一个模型属性验证模型属性?

Sails.js 如何根据Sails中的另一个模型属性验证模型属性?,sails.js,Sails.js,假设我有一个SailsJS中的发票模型。它有两个日期属性:issuedAt和dueAt。如何创建自定义验证规则来检查到期日期是否等于或大于发布日期 我尝试创建自定义规则,但似乎无法访问规则中的其他属性 module.exports = { schema: true, types: { duedate: function(dueAt) { return dueAt >= this.issuedAt // Doesn't work, "this" refers

假设我有一个SailsJS中的
发票
模型。它有两个日期属性:
issuedAt
dueAt
。如何创建自定义验证规则来检查到期日期是否等于或大于发布日期

我尝试创建自定义规则,但似乎无法访问规则中的其他属性

module.exports = {

  schema: true,

  types: {
    duedate: function(dueAt) {
      return dueAt >= this.issuedAt // Doesn't work, "this" refers to the function, not the model instance
    }
  },

  attributes: {

    issuedAt: {
      type: 'date'
    },

    dueAt: {
      type: 'date',
      duedate: true
    }

  }

};

beforeCreate方法在模型中作为第一个参数获取值。我在这里看到的这种验证的最佳场所

beforeCreate: (values, next){
  if (values.dueAt >= values.issuedAt) {
      return next({error: ['...']})
  }
  next()
}

我希望您现在能找到一个解决方案,但对于那些对一个好方法感兴趣的人,我将解释我的方法

不幸的是,正如您所说,您无法在属性验证功能中访问其他记录属性

@PawełWszoła为您提供了正确的方向,下面是一个完整的解决方案Sails@1.0.2:

// Get buildUsageError to construct waterline usage error
const buildUsageError = require('waterline/lib/waterline/utils/query/private/build-usage-error');

module.exports = {

  schema: true,

  attributes: {

    issuedAt: {
      type: 'ref',
      columnType: 'timestamp'
    },

    dueAt: {
      type: 'ref',
      columnType: 'timestamp'
    }

  },

  beforeCreate: (record, next) => {
    // This function is called before record creation so if callback method "next" is called with an attribute the creation will be canceled and the error will be returned 
    if(record.dueAt >= record.issuedAt){
      return next(buildUsageError('E_INVALID_NEW_RECORD', 'issuedAt date must be equal or greater than dueAt date', 'invoice'))
    }
    next();
  }

};

对我来说似乎不可能,调用规则没有绑定到函数。手动(或在数据库上)强制执行合同您好,此代码是否阻止创建模型?也就是说,Waterline是否正在查看next的参数以检查它是否为错误对象,并且在这种情况下停止了cretion过程?