简体   繁体   English

Sails.js水线ORM从乘法模型中删除数据

[英]Sails.js waterline ORM removing data from multiply models

Let's say I have got 2 models. 假设我有2个模型。

User and Clubs. 用户和俱乐部。

To simplify my problem let's say that User got only Id and Clubs got the ClubId and UserId so one club can have many different users. 为了简化我的问题,假设用户仅获得ID,而俱乐部获得了ClubId和UserId,因此一个俱乐部可以有许多不同的用户。

Here is my problem : 这是我的问题:

When I delete for example User with Id 3, I want also to delete all Users from Clubs with this Id 3. How to make it happen? 例如,当我删除I​​D为3的用户时,我还想从ID为3的俱乐部中删除所有用户。如何实现?

Sails doesn't support cascading deletes yet, but you can handle this yourself: Sails目前尚不支持级联删除,但是您可以自己处理:

User.destroy({id:3}).exec(function(err, users) {
   if (err) {return res.serverError();}
   var userIds = users.map(function(user){return user.id;});
   Club.destroy({user_id: userIds}).exec(function(err, clubs) {
      // do something
   });
});

destroy returns an array of all the objects that were destroyed. destroy返回所有已销毁对象的数组。 In your case, since you're searching by ID, only one would (hopefully) be returned, but if you were using criteria that could destroy several users at once you could still use the above code to wipe out all the related clubs. 在您的情况下,由于您是按ID进行搜索的,因此(希望)仅返回一个,但是如果您使用的标准可以一次销毁多个用户,则仍然可以使用上述代码清除所有相关俱乐部。

You can get afterDestroy event after deleting any model. 删除任何模型后都可以获取afterDestroy事件。 Simple demo as below 简单的演示如下

In comtroller : 在控制器中:

 Company.destroy({id: 12346798})
    .exec(function(e,r){

          return res.json(r);
    });

In Company.js model : 在Company.js模型中:

afterDestroy: function(destroyedCompany, cb) {

    var ids = _.pluck(destroyedCompany, 'id');

    if(ids && ids.length){

         Department.destroy({company_id: ids})
        .exec(function(e,r){
            CompanyArticle.destroy({company_id: ids}).exec(cb);
        });

    }
    else{
        cb();
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM