2016-04-24 107 views
0

用户模型查询相关BelongsToMany

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()); 
    }) 

上述工作,不过,我需要能够查询返回的慈善团体“的company_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})

回答

0

幸福感的差异,使用.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/