如何编写sails函数以在Controller中使用?

 韦韦韦骏轩_ 发布于 2023-01-31 09:30

我对sails js有疑问:

    如何在模型上编写sails函数?在Controler中使用?喜欢:

    beforeValidation/fn(values,cb)

    beforeCreate/fn(values,cb)

    afterCreate/fn(newlyInsertedRecord,cb)

Chad McEllig.. 8

如果您实际上尝试使用其中一个生命周期回调,语法将如下所示:

var uuid = require('uuid');
// api/models/MyUsers.js
module.exports = {
  attributes: {
    id: {
      type: 'string',
      primaryKey: true
    }
  },

  beforeCreate: function(values, callback) {
    // 'this' keyword points to the 'MyUsers' collection
    // you can modify values that are saved to the database here
    values.id = uuid.v4();
    callback();
  }
}

否则,您可以在模型上创建两种类型的方法:

实例方法

收集方法

放置在属性对象内的方法将是"实例方法"(在模型的实例上可用).即:

// api/models/MyUsers.js
module.exports = {
  attributes: {
    id: {
      type: 'string',
      primaryKey: true
    },
    myInstanceMethod: function (callback) {
      // 'this' keyword points to the instance of the model
      callback();
    }
  }
}

这将被用作:

MyUsers.findOneById(someId).exec(function (err, myUser) {
  if (err) {
    // handle error
    return;
  }

  myUser.myInstanceMethod(function (err, result) {
    if (err) {
      // handle error
      return;
    }

    // do something with `result`
  });
}

放置在属性对象外但在模型定义内的方法是"集合方法",即:

// api/models/MyUsers.js
module.exports = {
  attributes: {
    id: {
      type: 'string',
      primaryKey: true
    }
  },

  myCollectionMethod: function (callback) {
    // 'this' keyword points to the 'MyUsers' collection
    callback();
  }
}

收集方法将使用如下:

MyUsers.myCollectionMethod(function (err, result) {
  if (err) {
    // handle error
    return;
  }

  // do something with `result`
});

PS关于'this'关键字将是什么的评论假设您以正常方式使用这些方法,即以我在示例中描述的方式调用它们.如果以不同的方式调用它们(即保存对方法的引用并通过引用调用方法),那些注释可能不准确.

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有