用户模型
var User = db.Model.extend({
initialize: function() {
this.on('creating', this.generateId, this);
},
tableName: 'users',
hasTimestamps: true,
hidden: ['password'],
companies: function(){
return this.belongsToMany(
require('./company'),
'users_companies',
'user_id',
'company_id'
)
},
charities: function(){
return this.belongsToMany(
require('./charity'),
'users_charities',
'user_id',
'charity_id'
).withPivot(['company_id']);
},
generateId: function(model, attrs, options) {
model.set('id', uuid.v4());
}
});控制器
exports.getAllCharities = function(req, res){
new User({ id: req.user.id })
.charities()
.fetch()
.then(function(charities){
return res.json(charities.toJSON());
})然而,上面的工作,我需要能够查询返回的慈善机构,以过滤‘公司_id’的枢轴字段。尝试charities.where({company_id: 1}).fetch(),会产生一个异常,说明哪里不是慈善机构的功能。
找到了一个解决方案
new User({ id: req.user.id })
.charities()
.query('where', 'company_id', '=', req.query.companyid)
.fetch()
.then(function(charities){
return res.json(charities.toJSON())
})有人能解释一下这和使用.where({company_id: req.query.companyid})的区别吗?
发布于 2016-05-07 10:09:00
嗯,使用.where({company_id: req.query.companyid}),你基本上是把自己限制在“这个-相等-那个”上。如果你使用query,你可以取得更多的成就,例如.query('where', 'age', '>', 10)
此外,您还可以使用稍微不同的query,还可以使用knex查询生成器。例如:
new Person().query(function(qb) {
qb.whereIn('id', [2, 4]);
}).fetch().then(function(){});这样,您基本上可以访问knex.js提供的一切:http://knexjs.org/
https://stackoverflow.com/questions/36827028
复制相似问题