【问题标题】:Bookshelf JS Relation - Getting Count书架 JS 关系 - 计数
【发布时间】:2015-08-24 08:53:46
【问题描述】:

我正在尝试获取属于特定公司的用户数。

这是我的模型;

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”效果很好,没问题。
  • 方法“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 方法,我有点困惑(可能是因为承诺)

【问题讨论】:

    标签: node.js postgresql relational-database bookshelf.js


    【解决方案1】:

    Collection#count()

    如果您升级到 0.8.2,您可以使用新的Collection#count method

    Company.forge({id: req.params.id}).users().count().then(userCount =>
      res.send('company has ' + userCount + ' users!');
    );
    

    你的例子有问题

    users_count 方法的问题在于它试图让 Bookshelf 将您的查询结果转换为模型。

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

    见相关讨论here

    编辑:如何在您的属性中获取此信息。

    也许可以试试这样的:

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

    【讨论】:

    • 我认为你指的是 0.8.2。您的示例有效,谢谢,但这是另一个问题。我想将 users_count 作为公司模型属性。可能吗?顺便说一句,count将结果作为数组返回,这正常吗?我只需要一个整数。
    • 对不起,0.8.2 是正确的。它应该return an integer (or a string in the case of node-pg)。如果您收到不同的响应,则说明您发现了一个错误。请提出包含相关详细信息的issue
    • “公司模型属性” - 您的意思是希望计数显示为属性吗?
    • 这个解决方案是否也适用于 belongsToMany 关系?
    • @mezod 是的。如果有任何问题,请先尝试最新版本,然后在 Bookshelf 的 GitHub 页面上报告问题。
    【解决方案2】:

    查看bookshelf-eloquent 扩展名。 withCount() 函数可能是您正在寻找的。您的代码将如下所示:

    let company = await Company.where('id', req.params.id)
        .withCount('users').first();
    

    【讨论】:

    • 不错的catch兄弟,对于熟悉Laravel'sEloquentQuery-Builder的人来说,这是一个了不起的包。
    【解决方案3】:
    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");
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多