【问题标题】:Sails.js, Waterline and JoinsSails.js、水线和连接
【发布时间】:2015-01-03 00:11:37
【问题描述】:

我有两个具有多对多关联的模型:用户、项目

换句话说:用户属于任意数量的项目,项目属于任意数量的用户。

现在我想检索属于某个用户 ID 的所有项目。我怎样才能做到这一点?

以下查询返回我数据库中的所有项目,其中包含users 数组,当找到用户时,该数组具有一个属性,否则为空。

Projects.find().populate('users',{id : my_user_id}); 

项目模型

module.exports = {

  attributes: {
    name : {
      type : 'string',
      maxLength : 80,
      required : true
    },
    users : {
      collection : 'User',
      via : 'projects'
    },

  }
}

用户模型:

var User = {
  // Enforce model schema in the case of schemaless databases
  schema: true,

  attributes: {
    firstname  : {
      type: 'string',
      size : 60
    },
    lastname  : {
      type: 'string',
      size : 60
    },
    email     : {
      type: 'email',
      unique: true,
      required : true,
      size : 80

    },
    passports : {
      collection: 'Passport',
      via: 'user'
    },
    projects : {
      collection : 'Project',
      via : 'users'
    },
    toJSON: function() {
      var obj = this.toObject();
      delete obj.passports;
      delete obj.projects;
      return obj;
    }
  }
};

【问题讨论】:

  • 您应该发布模型定义的相关部分。

标签: sails.js waterline


【解决方案1】:

你必须反过来……也就是说,先找到用户,然后像这样填充项目关联:

User.findOne(userid)
    .populate('projects')
    .exec(function(err, projects) {
        // projects for that user returned
    });

【讨论】:

    【解决方案2】:

    @Melvin 的解决方案效果很好,但您也可以这样做:

    Project.find({users: [my_user_id, second_user_id]})
    .populate('users')
    .exec(function(err, projects) {
    
    });
    

    【讨论】:

      猜你喜欢
      • 2014-10-17
      • 2014-12-14
      • 1970-01-01
      • 1970-01-01
      • 2014-08-19
      • 2014-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多