书架JS关系 – 获取计数
我试图让用户数属于特定的公司。
这是我的模型;
var Company = Bookshelf.Model.extend({ tableName: 'companies', users: function () { return this.hasMany(User.Model, "company_id"); }, users_count : function(){ return new User.Model().query(function(qb){ qb.where("company_id",9); qb.count(); }).fetch(); }, organization: function () { return this.belongsTo(Organization.Model, "organization_id"); } });
- 方法“用户”工作得很好,没问题。
- 方法“users_count”查询运作良好,但不能得到“公司”模式的价值。
在路线上,我使用这样的书架模型;
new Company.Model({id:req.params.id}) .fetch({withRelated:['users']}) .then(function(model){ res.send(model.toJSON()) }) .catch(function(error){ res.send(error); });
我应该如何使用users_count方法,我有点困惑(可能是因为承诺)
收集#计数()
如果你升级到0.8.2,你可以使用新的Collection#count
方法 。
Company.forge({id: req.params.id}).users().count().then(userCount => res.send('company has ' + userCount + ' users!'); );
问题与你的例子
您的users_count
方法的问题在于它试图使书架将查询的结果转换为模型。
users_count : function(){ return new User.Model().query(function(qb){ qb.where("company_id",9); qb.count(); }).fetch(); // Fetch wanted an array of `user` records. },
这应该在这种情况下工作。
users_count : function(){ return new User.Model().query() .where("company_id",9) .count() },
请参阅相关讨论。
编辑:如何得到你的属性。
也许尝试这样的事情:
knex = bookshelf.knex; var Company = bookshelf.Model.extend({ tableName: 'companies', initialize: function() { this.on('fetching', function(model, attributes, options) { var userCountWrapped = knex.raw(this.getUsersCountQuery()).wrap('(', ') as user_count'); options.query.select('*', userCountWrapped); } } users: function () { return this.hasMany(User.Model, "company_id"); }, getUsersCountQuery: function() { return User.Model.query() .where("company_id",9) .count(); } organization: function () { return this.belongsTo(Organization.Model, "organization_id"); } });
看看书架 – 雄辩的扩展。 withCount()函数可能是你正在寻找的。 你的代码看起来像这样:
let company = await Company.where('id', req.params.id) .withCount('users').first();
User.collection().query(function (qb) { qb.join('courses', 'users.id', 'courses.user_id'); qb.groupBy('users.id'); qb.select("users.*"); qb.count('* as course_count'); qb.orderBy("course_count", "desc"); })