Sails.js 通过外键查询数据库

Sails.js query db by foreign key

我想知道如何使用默认的 Waterline 模型通过外键进行查询。

我有两个模型 Post 和类别 - Post 有一个外键类别。我需要这样查询:

Post.find({
  where: {
    category: query
  }
}).exec(function (err, data) {});

在这种情况下 query 是一个字符串,因此返回的结果应该是 Posts 包含搜索的类别。

最好的方法是什么?

注意:当前示例不起作用

了解如何使用类别 ID 实现此目的:

Category.find().where({ name: query }).exec(function (error, categories) {
   var catArr = [];

   if (categories.length) {
     categories.map(function (item) {
       catArr.push(item.id);
     });
   }

   Post.find().where({ category: catArr }).exec(function (error, posts) {
     // do stuff
   });

});

还必须像这样在模型中添加属性:

// Post
module.exports = {
  attributes: {
    name: {
       type: 'string'
    },
    category: {
       model: 'category'
    }
  }
};

// Category
module.exports = {
  attributes: {
    name: {
       type: 'string'
    },
    post: {
       model: 'post'
    }
  }
};

您的模型应该是

// Post
module.exports = {
  attributes: {
    name: {
       type: 'string'
    },
    category: {
       model: 'category'
    }
  }
};

// Category
module.exports = {
  attributes: {
    name: {
       type: 'string'
    },
    post: {
       collection: 'Post',
       via: 'category'
    }
  }
};

那么来自类别的查询将是

Category
    .find()
    .where({ name: query })
    .populateAll()
    .exec(function (error, categories) {
       var catArr = [];

       if (categories.length) {
         categories.map(function (item) {
           catArr.push(item.id);
         });
       }

       Post.find().where({ category: catArr }).exec(function (error, posts) {
         // do stuff
       });

    });

或者您可以通过

post查询它
Post
    .find()
    .where({ category: categoryId })
    .populateAll()
    .exec(function (error, posts) {
       // posts is all post with category that defined
    });

如果您想从 post 查询它,请确保您知道 categoryId。我通常使用 categoryId is string 和 slugify from name,所以我可以通过名称查询类别并确保类别名称(当然还有 ID)是唯一的。