防止删除相关的模型实例 - 环回3

问题描述 投票:1回答:1

我有两个型号:

User.json

"relations": {
    "items": {
        "type": "hasMany",
        "model": "Item",
        "foreignKey": "userid"
    },}

Item.json

"relations": {
    "user": {
        "type": "belongsTo",
        "model": "User",
        "foreignKey": "userid"
    },}

Loopback生成此端点:

DELETE / User / {userid} / items / {itemid}

我想覆盖默认删除方法,因此不会删除项目只有属性active将设置为false。

我的问题是:如何覆盖默认方法或阻止删除记录?

我试过了:

Item.once('attached',function(){
    Item.destroyById = function(filter,auth, cb){
        console.log('This is a overridden method')
    }
})

这似乎没有被执行。

和:

Item.observe('before delete', function(ctx, next) {  
    var err = new Error("Not deleted");  
    next(err)
});

它工作(项目没有删除)但抛出错误,我想避免。也许有办法将一些参数传递给next()方法?

javascript node.js loopbackjs
1个回答
1
投票

也许您可以为该操作实现连接器挂钩,您可以在其中动态修改数据库查询。

var connector = Model.getDataSource().connector;
connector.observe('before execute', function(ctx, next) {
  // preview your query and modify it as desired
  console.log(ctx);
  // so when you call next it will be executed in a shape you've created
  next();
});

这里有一些关于它的更多信息:https://loopback.io/doc/en/lb3/Connector-hooks.html

© www.soinside.com 2019 - 2024. All rights reserved.