在 Loopback 中将一个已经存在的模型传递给下一个

Pass an already existing Model to next in Loopback

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'});
};

@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()
 }    
 });
};

这只是向您展示如何使用更新、创建、查找、upsertwithwhere 等标签进行验证的示例代码,您必须在此处设置条件,它不会采用您在标签模型中定义的验证