将现有模型传递给Loopback中的下一个模型

时间:2018-11-20 08:53:18

标签: express model foreign-keys loopbackjs

Project个模型

{
  "name": "Project",
  "plural": "Projects",
  "base": "PersistedModel",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {
    "title": {
      "type": "string",
      "required": true
    },
    "description": {
      "type": "string"
    },
    "code": {
      "type": "string"
    },
    "startDate": {
      "type": "date",
      "required": true
    },
    "endDate": {
      "type": "date"
    },
    "value": {
      "type": "number"
    },
    "infoEN": {
      "type": "string"
    },
    "infoRU": {
      "type": "string"
    },
    "infoAM": {
      "type": "string"
    },
    "externalLinks": {
      "type": [
        "string"
      ]
    }
  },
  "validations": [],
  "relations": {
    "industry": {
      "type": "belongsTo",
      "model": "Industry",
      "foreignKey": "",
      "options": {
        "nestRemoting": true
      }
    },
    "service": {
      "type": "belongsTo",
      "model": "Service",
      "foreignKey": "",
      "options": {
        "nestRemoting": true
      }
    },
    "tags": {
      "type": "hasAndBelongsToMany",
      "model": "Tag",
      "foreignKey": "",
      "options": {
        "nestRemoting": true
      }
    }
  },
  "acls": [],
  "methods": {}
}

还有hasAndBelongsToMany标签

这是Tag模型

{
  "name": "Tag",
  "plural": "Tags",
  "base": "PersistedModel",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {
    "name": {
      "type": "string",
      "required": true
    }
  },
  "validations": [],
  "relations": {},
  "acls": [],
  "methods": {}
}

现在,在创建关系时,回送api会提供此api端点。

POST /Projects/{id}/tags

这将在标签集合中创建一个新标签并将其添加到项目中。 但是,将一个已经存在的标签添加到项目中怎么办?

所以我想也许我将before save钩子添加到Tag 在这里,我将检查标签是否存在,然后将现有标签传递给该关系。

这样的事情。

tag.js

'use strict';

module.exports = function(Tag) {
  Tag.observe('before save', function(ctx, next) {
    console.log(ctx.instance);
    Tag.find({name: ctx.instance.name})
    next();
  });
  // Tag.validatesUniquenessOf('name', {message: 'name is not unique'});
};

1 个答案:

答案 0 :(得分:1)

@HaykSafaryan只是一个演示,向您展示如何在项目中使用标签

var app = require('../../server/server');
module.exports = function(project) {
 var tag=app.models.tags
 //afterremote it just demo. you can use any method
 project.afterRemote('create', function(ctx, next) { 
 tag.find({name: ctx.instance.name},function(err,result)){
 if(err) throw err; 
  next()
 }    
 });
};

这只是示例代码,向您展示如何使用update,create,find,upsertwithwhere等标记进行验证,您必须在此处设置条件,而不会采用您在标记模型中定义的验证