帆:如何使用吃水线连接两个不同的模型
在MVC人们正在使用连接查询来join两个不同的表,但在sails.js我必须使用? 水线有什么方法?
基于你正在使用的数据库的答案。
例如,你需要在Mongo中填充值不要join。 或者如果你使用MySQL或类似的,你需要连接表。
简而言之,所有这些东西都通过水线覆盖。 所以你可以在关联的api/models
声明模型。 在Waterline适配器下执行连接和填充。
例如,你有User
和Comment
。
// api/models/User.js module.exports = { attributes: { name: { type: 'string' }, comments: { collection: 'Comment', via: 'user' } } }; // api/models/Comment.js module.exports = { attributes: { text: { type: 'string' }, user: { model: 'User', via: 'comments' } } };
然后你执行User.find()
并从数据库中获取已经join的\填充表。
但是,如果要执行手动join,则可以在Model实例上使用.populate()
方法。 例如:
// api/controllers/AnyController.js module.exports = { action: function(req, res) { User .findOne('ID_HERE') .populate('comments') .then(function(result) {}) .catch(function(error) {}); } };
你可以阅读更多关于在这里populate
– http://sailsjs.org/documentation/reference/waterline-orm/queries/populate