首页 > 解决方案 > 如何使用相关方法在书架中获取计数

问题描述

我正在尝试获得类似的计数值。它返回一个数组我只想知道是否有办法获取数组的计数

router.get('/uploads', (req, res) => {
  Image.query((image) => {
    image.orderBy('img_url', 'DESC');
    image.limit(10);

    // if you want to include the user with the image, you would use the withRelated
    // comments.user gets the user within the comments array
  })
    .fetchAll({
      withRelated: [
        'user',
        {
          comments: (qb) => {
            qb.orderBy('created_at', 'ASC');
          },
        },
        'comments.user',
       {
         likes: (qb) => {
          // how to get count for likes model its returning an array, i just want
          // count value
         }
       }
      ],
    })
    .then(images => res.status(200).json(images.toJSON()));
});

标签: javascriptnode.jsexpressknex.jsbookshelf.js

解决方案


通过添加 bookshelf-eloquent 来解决它,并添加withCount

现在路由器看起来像这样

router.get('/uploads', (req, res) => {
  Image.query((image) => {
    image.orderBy('img_url', 'DESC');
    image.limit(10);

    // if you want to include the user with the image, you would use the withRelated
    // comments.user gets the user within the comments array
  })
    .withCount('likes as likeCount')
    .fetchAll({
      withRelated: [
        'user',
        {
          comments: (qb) => {
            qb.orderBy('created_at', 'ASC');
          },
        },
        'comments.user',

      ],
    })
    .then(images => res.status(200).json(images.toJSON()));
});

推荐阅读