gpt4 book ai didi

javascript - 防止删除相关模型实例 - Loopback 3

转载 作者:行者123 更新时间:2023-11-30 19:47:22 24 4
gpt4 key购买 nike

我有两个模型:

User.json

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

Item.json

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

环回生成此端点:

删除 /User/{userid}/items/{itemid}

我想覆盖默认的删除方法,这样项目就不会被删除,只有属性 active 会被设置为 false

My question is: how can I override this default method or prevent deleting record?

我试过:

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() 方法?

最佳答案

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

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

关于javascript - 防止删除相关模型实例 - Loopback 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54828317/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com