在MVC中人们正在使用连接查询来加入两个不同的表,但是在sails.js中我必须使用什么?水线有什么方法吗?
答案 0 :(得分:2)
答案基于您正在使用的数据库。
例如,您需要在Mongo中填充值才能加入。或者,如果您使用MySQL或类似的东西,则需要连接表。
简而言之,所有这些东西都通过Waterline覆盖。所以你可以在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()
并从数据库中获取已加入\填充的表。
但是,如果要执行手动加入,可以在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